How to retrieve the intersection of multiple arrays in Java?

In Java, the intersection of multiple arrays can be obtained using the intersection operation of collection classes. Here is an example:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArrayIntersection {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {3, 4, 5, 6, 7};
        int[] arr3 = {5, 6, 7, 8, 9};

        Set<Integer> set1 = new HashSet<>(Arrays.asList([]::new)));
        for (int i = 1; i < 3; i++) {
            Set<Integer> set2 = new HashSet<>(Arrays.asList([]::new)));

        System.out.println("交集结果:" + set1);

In the example above, we used the HashSet class to create a temporary collection object, then converted the arrays to collections using the Arrays.asList() method, and finally used the retainAll() method to find the intersection of the two collections. Within the loop, we first found the intersection of the first and second arrays, then found the intersection with the third array to get the final intersection result.

The output result is: intersection result: [5]

Leave a Reply 0

Your email address will not be published. Required fields are marked *