java 并集、交集和集差的Java集合方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38768997/
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
Java collection methods for union, Intersection and set difference
提问by Daniel
I have written a program with 2 different collections of numbers and I was wondering how would I get the union, intersection and set difference from these two collections? I know that BitSet has methods for it but those doesn't work here.
我编写了一个包含 2 个不同数字集合的程序,我想知道如何从这两个集合中获得并集、交集和集差?我知道 BitSet 有它的方法,但这些方法在这里不起作用。
public class Collections {
public static void main(String[] args) {
// 1. Collection
Set<Integer> grp1 = new HashSet<Integer>();
grp1.add(1);
grp1.add(2);
grp1.add(3);
grp1.add(4);
grp1.add(5);
// printing 1. collection
System.out.println("1. collection: ");
Iterator<Integer> i = grp1.iterator();
while(i.hasNext()) {
int numbers1 = i.next();
System.out.print(numbers1 + " ");
}
System.out.println();
// 2. collection
Set<Integer> grp2 = new HashSet<Integer>();
grp2.add(8);
grp2.add(7);
grp2.add(6);
grp2.add(5);
grp2.add(4);
// printing 2. collection
System.out.println("2. collection: ");
Iterator<Integer> y = grp2.iterator();
while(y.hasNext()) {
int numbers2 = y.next();
System.out.print(numbers2 + " ");
// Union
// Intersection
// Difference
}
}
}
回答by Jean Logeart
Union:
联盟:
Set<Integer> union = new HashSet<>(grp1);
union.addAll(grp2);
Intersection:
路口:
Set<Integer> intersection = new HashSet<>(grp1);
intersection.retainAll(grp2);
Difference:
不同之处:
Set<Integer> diff = new HashSet<>(grp1);
diff.removeAll(grp2);
回答by Sean Patrick Floyd
Guavahas these operations in it's Sets
class.
Set<Integer> union = Sets.union(set1, set2);
Set<Integer> intersection = Sets.intersection(set1, set2);
Set<Integer> difference = Sets.difference(set1, set2);
All of these return unmodifiable views, backed by the original Sets.
所有这些都返回不可修改的视图,由原始 Sets 支持。