Java 集的并集或交集

Union or intersection of Java Sets

在 Java 中创建 Set 的并集或交集的最简单方法是什么?对于这个简单的问题,我已经看到了一些奇怪的解决方案(例如手动迭代这两个集合)。

最简单的单行解决方案是这样的:

set1.addAll(set2); // Union
set1.retainAll(set2); // Intersection

以上解决方案破坏性,意思是原来的内容set1我改了
如果您不想修改现有的集合,请创建一个新集合:

var result = new HashSet<>(set1);          // In Java 10 and above
Set<Integer> result = new HashSet<>(set1); // In Java < 10
result.addAll(set2); // Union
result.retainAll(set2); // Intersection

您可以使用 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");

现在,正在计算 Java 中两个集合的交集:

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

输出: Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]

类似地,计算Java中两个集合的并集:

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

输出: 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/

阅读更多关于 guava 库的信息

为了将番石榴库添加到您的项目中,您可以查看

虽然番石榴肯定更整洁并且几乎是标准的,但这里有一种非破坏性的方法来完成 unionintersect 仅使用标准 Java

Set s1 = Set.of(1,2,3);
Set s2 = Set.of(3,4,5);     

Set union = Stream.concat(s1.stream(),s2.stream()).collect(Collectors.toSet()); 
Set intersect = s1.stream().filter(s2::contains).collect(Collectors.toSet());
    import java.util.*;

public class sets {
    public static void swap(int array[], int a, int b) { // Swap function for sorting
        int temp = array[a];
        array[a] = array[b];
        array[b] = temp;
    }

    public static int[] sort(int array[]) { // sort function for binary search (Selection sort)
        int minIndex;
        int j;
        for (int i = 0; i < array.length; i++) {
            minIndex = i;
            for (j = i + 1; j < array.length; j++) {
                if (array[minIndex] > array[j])
                    minIndex = j;
            }
            swap(array, minIndex, i);
        }
        return array;
    }

    public static boolean search(int array[], int search) { // Binary search for intersection and difference
        int l = array.length;
        int mid = 0;
        int lowerLimit = 0, upperLimit = l - 1;
        while (lowerLimit <= upperLimit) {
            mid = (lowerLimit + upperLimit) / 2;
            if (array[mid] == search) {
                return true;
            } else if (array[mid] > search)
                upperLimit = mid - 1;
            else if (array[mid] < search)
                lowerLimit = mid + 1;
        }
        return false;
    }

    public static int[] append(int array[], int add) { // To add elements
        int newArray[] = new int[array.length + 1];
        for (int i = 0; i < array.length; i++) {
            newArray[i] = array[i];
        }
        newArray[array.length] = add;
        newArray = sort(newArray);
        return newArray;
    }

    public static int[] remove(int array[], int index) { // To remove duplicates
        int anotherArray[] = new int[array.length - 1];
        int k = 0;
        if (array == null || index < 0 || index > array.length) {
            return array;
        }
        for (int i = 0; i < array.length; i++) {
            if (index == i) {
                continue;
            }
            anotherArray[k++] = array[i];
        }
        return anotherArray;
    }

    public static void Union(int A[], int B[]) { // Union of a set
        int union[] = new int[A.length + B.length];
        for (int i = 0; i < A.length; i++) {
            union[i] = A[i];
        }
        for (int j = A.length, i = 0; i < B.length || j < union.length; i++, j++) {
            union[j] = B[i];
        }
        for (int i = 0; i < union.length; i++) {
            for (int j = 0; j < union.length; j++) {
                if (union[i] == union[j] && j != i) {
                    union = remove(union, j); // Removing duplicates
                }
            }
        }
        union = sort(union);
        System.out.print("A U B = {"); // Printing
        for (int i = 0; i < union.length; i++) {
            if (i != union.length - 1)
                System.out.print(union[i] + ", ");
            else
                System.out.print(union[i] + "}");
        }
    }

    public static void Intersection(int A[], int B[]) {
        int greater = (A.length > B.length) ? (A.length) : (B.length);
        int intersect[] = new int[1];
        int G[] = (A.length > B.length) ? A : B;
        int L[] = (A.length < B.length) ? A : B;
        for (int i = 0; i < greater; i++) {
            if (search(L, G[i]) == true) { // Common elements
                intersect = append(intersect, G[i]);
            }
        }
        for (int i = 0; i < intersect.length; i++) {
            for (int j = 0; j < intersect.length; j++) {
                if (intersect[i] == intersect[j] && j != i) {
                    intersect = remove(intersect, j); // Removing duplicates
                }
            }
        }
        System.out.print("A ∩ B = {"); // Printing
        for (int i = 1; i < intersect.length; i++) {
            if (i != intersect.length - 1)
                System.out.print(intersect[i] + ", ");
            else
                System.out.print(intersect[i] + "}");
        }
    }

    public static void difference(int A[], int B[]) {
        int diff[] = new int[1];
        int G[] = (A.length > B.length) ? A : B;
        int L[] = (A.length < B.length) ? A : B;
        int greater = G.length;
        for (int i = 0; i < greater; i++) {
            if (search(L, G[i]) == false) {
                diff = append(diff, G[i]); // Elements not in common
            }
        }
        for (int i = 0; i < diff.length; i++) {
            for (int j = 0; j < diff.length; j++) {
                if (diff[i] == diff[j] && j != i) {
                    diff = remove(diff, j); // Removing duplicates
                }
            }
        }
        System.out.println("Where A is the larger set, and B is the smaller set.");
        System.out.print("A - B = {"); // Printing
        for (int i = 1; i < diff.length; i++) {
            if (i != diff.length - 1)
                System.out.print(diff[i] + ", ");
            else
                System.out.print(diff[i] + "}");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the operation");
        String operation = sc.next().toLowerCase();
        System.out.println("Enter the length of the first set.");
        int l1 = sc.nextInt();
        System.out.println("Enter the length of the second set.");
        int l2 = sc.nextInt();
        int A[] = new int[l1];
        int B[] = new int[l2];
        System.out.println("Enter the elements of the first set.");
        System.out.print("A = ");
        for (int i = 0; i < l1; i++) {
            A[i] = sc.nextInt();
        }
        System.out.println("Enter the elements of the second set.");
        System.out.print("B = ");
        for (int i = 0; i < l2; i++) {
            B[i] = sc.nextInt();
        }
        A = sort(A); // Sorting the sets before passing
        B = sort(B);
        sc.close();
        switch (operation) {
            case "union":
                Union(A, B);
                break;
            case "intersection":
                Intersection(A, B);
                break;
            case "difference":
                difference(B, A);
                break;
            default:
                System.out.println("Invalid Operation");
        }
    }
}