# JAVA List 数组取交集和差集

### 今天无意间去菜鸟教程（ www.runoob.com ）翻了一下JAVA基础，发现了一个意外的惊喜，就是关于对两个List 集合进行取交集和差集的方法，感觉十分受用，因为自己在之前做项目的时候，确实有碰到过类似的需求，所以在此刻记录下来，与各位技术同行分享一下。

1.取交集

/**
* @Description: 取交集
*/
public static void listJiaoJI(){
List<String> list1 = new ArrayList<String>();

List<String> list2 = new ArrayList<String>();

list2.remove(1);
list2.remove("age");

System.out.println("list1: \n"+String.join(",", list1));
System.out.println("list2: \n"+String.join(",", list2));

// retainAll 表示取集合中有相同的值
boolean contain = list2.retainAll(list1);
System.out.println("是否含有交集："+contain+"\n交集: "+String.join(",", list2));
}

list1:
names,age,sex,weight
list2:
names,sex,weight,job,family

1.取差集

/**
* @Description: 取差集
*/
public static void listChaJi(){

list2.remove(1);

System.out.println("list1: ");
for(int i = 0; i < list1.size(); i++ ){
if(0 == i){
System.out.print(list1.get(i));
continue;
}
System.out.print(","+list1.get(i));
}

System.out.println("\nlist2: ");
for(int i = 0; i < list2.size(); i++ ){
if(0 == i){
System.out.print(list2.get(i));
continue;
}
System.out.print(","+list2.get(i));
}

list2.removeAll(list1);

System.out.println("\n差集: ");
for(int i = 0; i < list2.size(); i++ ){
if(0 == i){
System.out.print(list2.get(i));
continue;
}
System.out.print(","+list2.get(i));
}
}

list1:
88,99,1566,352
list2:
88,1566,352,666,111

666,111