Java集合的并集或交集

bq3bfh9z  于 2022-12-28  发布在  Java
关注(0)|答案(5)|浏览(151)

在Java中,创建Set的并集或交集最简单的方法是什么?我见过一些奇怪的解决方案(例如,手动迭代两个集合)。

6mw9ycah

6mw9ycah1#

最简单的单行解决方案如下:

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

上面的解决方案是破坏性的,意味着原始 * set1 * my的内容被更改。
如果您不想修改现有集,请创建一个新集:
一个一个二个一个一个一个三个一个一个一个一个一个四个一个

q9yhzks0

q9yhzks02#

虽然guava确实更简洁,也更标准,但这里有一种只使用标准Java的非破坏性方法来执行unionintersect

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

ycggw6v23#

您可以使用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库的信息
为了将Guava库添加到您的项目中,您可以查看https://stackoverflow.com/a/4648947/8258942

wf82jlnq

wf82jlnq4#

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");
        }
    }
}
rxztt3cl

rxztt3cl5#

当我想到 unionintersection 时,它在第一个循环中是对集合的 * 操作,也就是Map
集x集→集
不清楚,为什么它会出现在Java设计中。

static <T> Set<T> union(Set<T> a, Set<T> b)
{
    Set<T> res = new HashSet<T>(a);
    res.addAll(b);
    return res;
}

static <T> Set<T> intersection(Set<T> a, Set<T> b)
{
    Set<T> res = new HashSet<T>(a);
    res.retainAll(b);
    return res;
}

相关问题