答案 0 :(得分:9)
最简单的单行解决方案是这样:
set1.addAll(set2); // Union
set1.retainAll(set2); // Intersection
上述解决方案是破坏性的,这意味着我对原始 set1 的内容进行了更改。如果您不想触摸现有集合,请创建一个新集合:
Set<E> result = new HashSet<>(set1);
// └─ your specific type
result.addAll(set2); // Union
result.retainAll(set2); // Intersection
答案 1 :(得分:2)
虽然番石榴肯定是更整洁且非常标准的,但这是一种仅使用标准Java进行合并和相交的非破坏性方法
Set s1 = Set.of(1,2,3);
Set s2 = Set.of(3,4,5);
Set union = Stream.concat(s1.stream(),s2.stream()).toSet();
Set intersect = s1.stream().filter(s2::contains).toSet();
答案 2 :(得分:1)
您可以使用Google's Guava library
来实现。下面借助示例给出以下说明:
// Set a
Set<String> a = new HashSet<String>();
a.add("x");
a.add("y");
a.add("z");
// Set b
Set<String> b = new HashSet<String>();
b.add("x");
b.add("p");
b.add("q");
现在,用Java计算两个Set的交集:
Set<String> intersection = Sets.intersection(a, b);
System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
a.toString(), b.toString(), intersection.toString());
输出: Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]
同样,用Java计算两个集合的并集:
Set<String> union = Sets.union(a, b);
System.out.printf("Union of two Set %s and %s in Java is %s %n",
a.toString(), b.toString(), union.toString());
输出: Union of two Set [z, y, x] and [q, p, x] in Java is [q, p, x, z, y]
您可以在https://google.github.io/guava/releases/18.0/api/docs/上了解有关番石榴库的更多信息
为了将番石榴库添加到您的项目中,您可以看到https://stackoverflow.com/a/4648947/8258942