java中两个list集合取并集,交集和差集的方法
引入jar包 commons-collections
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
public class Test {
public static void main(String[] args) {
List<Student> list1 = new ArrayList<Student>();
List<Student> list2 = new ArrayList<Student>();
Student student1 = new Student().setId("1").setName("张三");
Student student2 = new Student().setId("2").setName("李四");
Student student3 = new Student().setId("2").setName("李四");
Student student4 = new Student().setId("3").setName("王五");
list1.add(student1);
list1.add(student2);
list2.add(student3);
list2.add(student4);
List<Student> union = getUnion(list1,list2);
System.out.println("并集:"+union);
List<Student> intersection = getIntersection(list1,list2);
System.out.println("交集:"+intersection);
List<Student> disjunction = getDisjunction(list1,list2);
System.out.println("交集的补集:"+disjunction);
List<Student> subtract = getSubtract(list1,list2);
System.out.println("差集:"+subtract);
}
//获取两个集合并集(自动去重)
public static List<Student> getUnion(List<Student> list1,List<Student> list2){
List<Student> union = (List<Student>)CollectionUtils.union(list1, list2);
return union;
}
//获取两个集合交集
public static List<Student> getIntersection(List<Student> list1,List<Student> list2){
List<Student> intersection = (List<Student>)CollectionUtils.intersection(list1, list2);
return intersection;
}
//获取两个集合交集的补集 即 list1 + list2 - 交集
public static List<Student> getDisjunction(List<Student> list1,List<Student> list2){
List<Student> disjunction = (List<Student>)CollectionUtils.disjunction(list1, list2);
return disjunction;
}
//获取两个集合的差集 list1 - 交集
public static List<Student> getSubtract(List<Student> list1,List<Student> list2){
List<Student> subtract = (List<Student>)CollectionUtils.subtract(list1, list2);
return subtract;
}
}
还没有评论,来说两句吧...