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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:44:40  来源:igfitidea点击:

Java collection methods for union, Intersection and set difference

java

提问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 Setsclass.

Guava在它的Sets类中有这些操作。

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 支持。

See Guava Explained-> Collection Utilities-> Sets

参见番石榴解释->集合实用程序->集合