java中两个list集合取并集,交集和差集的方法

心已赠人 2023-03-12 12:11 86阅读 0赞

引入jar包 commons-collections

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-collections4</artifactId>
  4. <version>4.1</version>
  5. </dependency>
  6. public class Test {
  7. public static void main(String[] args) {
  8. List<Student> list1 = new ArrayList<Student>();
  9. List<Student> list2 = new ArrayList<Student>();
  10. Student student1 = new Student().setId("1").setName("张三");
  11. Student student2 = new Student().setId("2").setName("李四");
  12. Student student3 = new Student().setId("2").setName("李四");
  13. Student student4 = new Student().setId("3").setName("王五");
  14. list1.add(student1);
  15. list1.add(student2);
  16. list2.add(student3);
  17. list2.add(student4);
  18. List<Student> union = getUnion(list1,list2);
  19. System.out.println("并集:"+union);
  20. List<Student> intersection = getIntersection(list1,list2);
  21. System.out.println("交集:"+intersection);
  22. List<Student> disjunction = getDisjunction(list1,list2);
  23. System.out.println("交集的补集:"+disjunction);
  24. List<Student> subtract = getSubtract(list1,list2);
  25. System.out.println("差集:"+subtract);
  26. }
  27. //获取两个集合并集(自动去重)
  28. public static List<Student> getUnion(List<Student> list1,List<Student> list2){
  29. List<Student> union = (List<Student>)CollectionUtils.union(list1, list2);
  30. return union;
  31. }
  32. //获取两个集合交集
  33. public static List<Student> getIntersection(List<Student> list1,List<Student> list2){
  34. List<Student> intersection = (List<Student>)CollectionUtils.intersection(list1, list2);
  35. return intersection;
  36. }
  37. //获取两个集合交集的补集 即 list1 + list2 - 交集
  38. public static List<Student> getDisjunction(List<Student> list1,List<Student> list2){
  39. List<Student> disjunction = (List<Student>)CollectionUtils.disjunction(list1, list2);
  40. return disjunction;
  41. }
  42. //获取两个集合的差集 list1 - 交集
  43. public static List<Student> getSubtract(List<Student> list1,List<Student> list2){
  44. List<Student> subtract = (List<Student>)CollectionUtils.subtract(list1, list2);
  45. return subtract;
  46. }
  47. }

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读