← 中文资源

简体中文版本

HashSet 集合运算:并集、交集、差集

用 addAll、retainAll、removeAll 在 HashSet 上做 union/intersection/difference:先拷贝再操作,避免污染原集合,标签比对一次算完,不必手写循环。

阅读英文原文

实现说明

整个示例围绕类 ReleaseSets和函数 main组织。

使用要点

  • 演示输出是带标签的(union:、intersection:、difference:),每个操作都会留下自己的一行标注。

常见问题

运行「HashSet 集合运算:并集、交集、差集」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 union:、intersection:、difference: 标签标明各步骤。

核心语句

Set<String> hotfixed = new HashSet<>(Set.of("billing", "search", "email"));
Set<String> deployed = new HashSet<>(Set.of("auth", "billing", "search"));
Set<String> intersection = new HashSet<>(deployed);

代码示例

import java.util.HashSet;
import java.util.Set;

public class ReleaseSets {

    public static void main(String[] args) {
        Set<String> deployed = new HashSet<>(Set.of("auth", "billing", "search"));
        Set<String> hotfixed = new HashSet<>(Set.of("billing", "search", "email"));

        // union 并集:先拷贝再 addAll,避免污染 deployed 原集合
        Set<String> union = new HashSet<>(deployed);
        union.addAll(hotfixed);
        System.out.println("union: " + union);

        // intersection 交集:retainAll 保留两边都出现的服务,需要回归验证
        Set<String> intersection = new HashSet<>(deployed);
        intersection.retainAll(hotfixed);
        System.out.println("intersection: " + intersection);

        // difference 差集:removeAll 拿到 deployed 有而 hotfix 没碰过的部分
        Set<String> difference = new HashSet<>(deployed);
        difference.removeAll(hotfixed);
        System.out.println("difference: " + difference);
    }
}