在java语言中建立Set的并集或交集最简单的方法是什么?对于这个简单的问题,我看到了一些奇怪的解决方案(例如,手动迭代两个集合)。
发布于 2018-06-30 16:23:18
最简单的一行解决方案是:
set1.addAll(set2); // Unionset1.retainAll(set2); // Intersection上面的解决方案是破坏性的,也就是说原来的set1的内容我改变了。
如果您不想接触现有的设置,请创建一个新的设置:
Set<E> result = new HashSet<>(set1);
// └─ your specific typeresult.addAll(set2); // Unionresult.retainAll(set2); // Intersection发布于 2018-12-07 06:47:25
虽然芭乐肯定更整洁,而且几乎是标准的,但这里有一种仅使用标准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());发布于 2018-06-30 16:34:40
您可以使用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<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/上阅读有关芭乐图书馆的更多信息
为了将guava库添加到项目中,您可以看到https://stackoverflow.com/a/4648947/8258942
https://stackoverflow.com/questions/51113134
复制相似问题