java Set 的并集和交集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51113134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Union and intersection of java Sets
提问by Mahozad
采纳答案by Mahozad
The simplest one-line solution is this:
最简单的单行解决方案是这样的:
set1.addAll(set2); // Union
set1.retainAll(set2); // Intersection
The above solution is destructivemeaning that contents of the original set1my change. If you don't want to touch your existing sets, create a new set:
上述解决方案是破坏性的,这意味着我更改了原始set1 的内容。如果您不想接触现有的集合,请创建一个新集合:
Set<E> result = new HashSet<>(set1);
// └─ your specific type
result.addAll(set2); // Union
result.retainAll(set2); // Intersection
回答by Nitin Bisht
You can achieve this using Google's Guava library
. The following explanation is given below with the help of an example:
您可以使用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");
Now, Calculating Intersection of two Set in Java:
现在,在 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());
Output:Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]
输出:Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]
Similarly, Calculating Union of two Set in Java:
同样,Java 中计算两个 Set 的并集:
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());
Output:Union of two Set [z, y, x] and [q, p, x] in Java is [q, p, x, z, y]
输出:Union of two Set [z, y, x] and [q, p, x] in Java is [q, p, x, z, y]
You can read more about guava library at https://google.github.io/guava/releases/18.0/api/docs/
您可以在https://google.github.io/guava/releases/18.0/api/docs/阅读有关番石榴库的更多信息
In order to add guava library to your project, You can see https://stackoverflow.com/a/4648947/8258942
为了将番石榴库添加到您的项目中,您可以看到https://stackoverflow.com/a/4648947/8258942
回答by David Lilljegren
While guava for sure is neater and pretty much standard, here's a non destructive way to do unionand intersectusing only standard Java
虽然 guava 确实更整洁,而且非常标准,但这是一种仅使用标准 Java进行联合和相交的非破坏性方法
Set s1 = Set.of(1,2,3);
Set s2 = Set.of(3,4,5);
Set union = Stream.concat(s1.stream(),s2.stream()).collect(Collectors.toSet());
Set intersect = s1.stream().filter(s2::contains).collect(Collectors.toSet());