Java Program to Find Union and Intersection of Arrays in Java

Java Program to Find Union and Intersection of Arrays in Java thumbnail
9K
By Dhiraj Ray 17 February, 2020

Writing a Java program to find first non-repeated character in a String is a common programming interview question to test the usage of Set interface provided in Java collection framework.

The solution of this program can be built with a plain for-each loop by traversing each element of the array and manually identifying the duplicates before performing any insert operation but we will be using in-built data structure in Java known as HashSet to provide solution to this question.

HashSet implements the Set interface and does not allow duplicate elements. These particular feature can be used to find the union of multiple arrays whereas retainAll() method provided in Set interface can be used to find the intersection of multiple arrays.

retainAll() removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Below is the complete Java program implementation:

package com.devglan;

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

public class ArrayUnionAndIntersection {

    public static Set findUnion(Integer[] ... arrays){
        Set set = new HashSet<>();
        Stream.of(arrays).forEach(array -> set.addAll(Arrays.asList(array)));
        return set;
    }

    public static Set findIntersection(Integer[] ... arrays){
        Set intersectionSet = new HashSet<>(Arrays.asList(arrays[0]));
        Stream.of(arrays).skip(1).forEach(array -> {
            HashSet set = new HashSet<>(Arrays.asList(array));
            intersectionSet.retainAll(set);
        });
        return intersectionSet;
    }

    public static void main(String[] args){
        Integer[] firstArray = {9, 7, 6, 7, 1, 8};

        Integer[] secondArray = {5, 2, 6, 3, 4};

        Integer[] thirdArray = {4, 7, 5, 6};
        Set union = findUnion(firstArray, secondArray, thirdArray);
        System.out.println("Output Array after union ***********************");
        System.out.println(union);

        Set intersection = findIntersection(firstArray, secondArray, thirdArray);
        System.out.println("Output Array after intersection ***********************");
        System.out.println(intersection);
    }
}

Output:
java-union-and-intersection-of-arrays-output

Explanation

The findUnion() method first creates a Stream object from the input arrays and adds each element of the array to a Set. As a Set does not allow any duplicates, we get all the unique elements from the multiple arrays and hence the union is calculated.

The findIntersection() method first creates an HashSet from the first input array so that retailAll() method can be applied on this Set with the remaining arrays to find the intersection of multiple arrays. We have used skip() stream operation while performing the for each to retain elements from remaining arrays.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.