Mah*_*zad 3 java collections set set-intersection set-union
Set在java中建立联合或s 交集的最简单方法是什么?我已经看到了这个简单问题的一些奇怪的解决方案(例如手动迭代这两个集合).
Mah*_*zad 11
最简单的单行解决方案是:
set1.addAll(set2); // Union
Run Code Online (Sandbox Code Playgroud)
set1.retainAll(set2); // Intersection
Run Code Online (Sandbox Code Playgroud)
以上解决方案具有破坏性,意味着原始set1的内容发生了变化.如果您不想触摸现有的集,请创建一个新集:
Set<E> result = new HashSet<>(set1);
// ?? your specific type
Run Code Online (Sandbox Code Playgroud)
result.addAll(set2); // Union
Run Code Online (Sandbox Code Playgroud)
result.retainAll(set2); // Intersection
Run Code Online (Sandbox Code Playgroud)
您可以使用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");
Run Code Online (Sandbox Code Playgroud)
现在,在 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());
Run Code Online (Sandbox Code Playgroud)
输出: Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]
同样,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());
Run Code Online (Sandbox Code Playgroud)
输出: 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/阅读有关番石榴库的更多信息
为了将番石榴库添加到您的项目中,您可以看到/sf/answers/325426321/
虽然番石榴肯定是更整洁和相当标准的,但这是一种仅使用标准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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13259 次 |
| 最近记录: |