我编写了一个包含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
}
}
}
答案 0 :(得分:10)
联:
Set<Integer> union = new HashSet<>(grp1);
union.addAll(grp2);
路口:
Set<Integer> intersection = new HashSet<>(grp1);
intersection.retainAll(grp2);
差异:
Set<Integer> diff = new HashSet<>(grp1);
diff.removeAll(grp2);
答案 1 :(得分:4)
Set<Integer> union = Sets.union(set1, set2);
Set<Integer> intersection = Sets.intersection(set1, set2);
Set<Integer> difference = Sets.difference(set1, set2);
所有这些都返回不可修改的视图,由原始集支持。