Java 并集、交集和差集的集合方法

标签 java

我编写了一个包含两个不同数字集合的程序,我想知道如何从这两个集合中获得并集、交集和集合差?我知道 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

         }
     }

}

最佳答案

联盟:

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);

关于Java 并集、交集和差集的集合方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38768997/

相关文章:

java - 插入到 `table` 不存在的地方

java - 为什么我们对 float 据类型使用 `f`,而不对字节和短整型数据类型使用 0x104567910?

java - ActionListener 内的递归

java - 内部错误 : Unknown or unimplemented accessor type: 9

java - J2EE - 如何从服务器响应中删除空格、空行

java - 我无法在 Eclipse 中输入花括号

java - 一次性数据转换的JDBC批量更新

java - Selenium CTRL 和单击不起作用?

java - 为什么在 Java 中进行交易之前要与 BigDecimal.ONE 比较余额?

java - 如何检查文件/内容是否有乱码?