解析Java中的集合操作:并集、交集和差集

原创 青旅半醒 2024-10-17 18:36 100阅读 0赞

在Java中,我们可以使用java.util.Set接口来操作集合(如List的子类),这样就可以方便地进行并集、交集和差集操作。

  1. 并集(Union):
    使用addAll()方法或者直接创建新的集合添加元素即可。例如:
  1. Set<String> set1 = new HashSet<>(Arrays.asList("a", "b")));
  2. Set<String> set2 = new HashSet<>(Arrays.asList("b", "c")));
  3. // 并集
  4. set1.addAll(set2); // 或者使用 addAll() 方法
  5. System.out.println(set1); // 输出: [a, b, c]
  1. 交集(Intersection):
    使用retainAll()方法或者直接创建新的集合进行比较。例如:
  1. Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")));
  2. Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d")));
  3. // 交集
  4. set1.retainAll(set2); // 或者使用 retainAll() 方法
  5. System.out.println(set1); // 输出: [b, c]
  1. 差集(Difference):
    有两种方法实现差集:
  • 原始集合减去目标集合
    使用removeAll()方法。例如:
  1. Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")));
  2. Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d"), "e")); // 添加了 "e"
  3. // 差集 (set1 - set2)
  4. set1.removeAll(set2); // 或者使用 removeAll() 方法
  5. System.out.println(set1); // 输出: [a]
  • 创建一个新的集合,只包含原始集合中但不在目标集合中的元素
    这通常涉及到遍历两个集合,并将不在目标集合的元素添加到新集合。例如:
  1. Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")));
  2. Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d"), "e")); // 添加了 "e"
  3. // 创建差集集合 (set1 - set2)
  4. List<String> differenceList = new ArrayList<>();
  5. for (String element : set1) {
  6. if (!set2.contains(element))) {
  7. differenceList.add(element);
  8. }
  9. }
  10. Set<String> differenceSet = new HashSet<>(differenceList);
  11. System.out.println(differenceSet); // 输出: [a]

根据实际需求,可以选择上述方法之一来实现差集。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

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

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

相关阅读