JAVA集合求交集,并集,对称差

红太狼 2022-05-24 10:46 360阅读 0赞

JAVA集合求交集,并集,对称差

  • 求两个集合的交集:retainAll()方法
  • 求两个集合的交集:addAll()方法
  • 求两个集合的对称差(A-B)并(B-A)}:removeAll()方法 和 addAll()方法

下面是例子说明:

求两个集合的交集:retainAll()方法

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. // TODO Auto-generated method stub
  5. //求两个集合的交集
  6. Scanner scanner=new Scanner(System.in);
  7. TreeSet<Character> list1=new TreeSet<Character>();
  8. TreeSet<Character> list2=new TreeSet<Character>();
  9. for(int i=1;i<=4;i++)
  10. {
  11. list1.add(scanner.next().charAt(0));
  12. }
  13. for(int i=1;i<=4;i++)
  14. {
  15. list2.add(scanner.next().charAt(0));
  16. }
  17. //求两个集合的交集retainAll()
  18. list1.retainAll(list2);
  19. Iterator<Character> it=list1.iterator();
  20. while(it.hasNext())
  21. {
  22. Character c=(Character) it.next();
  23. System.out.print(c+" ");
  24. }
  25. }
  26. }

这里写图片描述

求两个集合的交集:addAll()方法

  1. import java.util.*;
  2. public class jihe {
  3. public static void main(String[] args) {
  4. // TODO Auto-generated method stub
  5. //求两个集合的并集
  6. Scanner scanner=new Scanner(System.in);
  7. TreeSet<Character> list1=new TreeSet<Character>();
  8. TreeSet<Character> list2=new TreeSet<Character>();
  9. for(int i=1;i<=4;i++)
  10. {
  11. list1.add(scanner.next().charAt(0));
  12. }
  13. for(int i=1;i<=4;i++)
  14. {
  15. list2.add(scanner.next().charAt(0));
  16. }
  17. //求两个集合的并集addAll()
  18. list1.addAll(list2);
  19. Iterator<Character> it=list1.iterator();
  20. while(it.hasNext())
  21. {
  22. Character c=(Character) it.next();
  23. System.out.print(c+" ");
  24. }
  25. }
  26. }

这里写图片描述

求两个集合的对称差(A-B)并(B-A)}:removeAll()方法 和 addAll()方法

  1. import java.util.*;
  2. public class jihe {
  3. public static void main(String[] args) {
  4. // TODO Auto-generated method stub
  5. //求两个集合的对称差
  6. Scanner scanner=new Scanner(System.in);
  7. TreeSet<Character> list1=new TreeSet<Character>();
  8. TreeSet<Character> list2=new TreeSet<Character>();
  9. for(int i=1;i<=4;i++)
  10. {
  11. list1.add(scanner.next().charAt(0));
  12. }
  13. for(int i=1;i<=4;i++)
  14. {
  15. list2.add(scanner.next().charAt(0));
  16. }
  17. //求两个集合的对称差 A-B 并 B-A “-”号:removeAll()方法
  18. TreeSet<Character> list3=new TreeSet<Character>();
  19. list3=(TreeSet<Character>) list1.clone(); //克隆list1
  20. list1.removeAll(list2);//A-B放在list1中
  21. list2.removeAll(list3);//B-A放在list2中
  22. list1.addAll(list2);//求A与B的并集
  23. Iterator<Character> it=list1.iterator();
  24. while(it.hasNext())
  25. {
  26. Character c=(Character) it.next();
  27. System.out.print(c+" ");
  28. }
  29. }
  30. }

这里写图片描述

发表评论

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

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

相关阅读