Java Program to Find Union and Intersection of Two Arrays

«
»

This is the Java Program to Find the Union and Intersection of 2 Arrays.

Problem Description

Given two arrays of integers, find and print the union and intersection of the arrays.

advertisement

Example:
Array: [1,2,3,4,5]

Array1: [5,3,6,7,9]

Output:
Union = [1,2,3,4,5,6,7,9]

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Intersection = [3,5]

Problem Solution

Create two sets called union and intersection. To find the union, add the first array’s elements to the set union. Now, add all the second array elements if they are not present in the set union. To find the intersection, find the common elements and add them to the set.

Program/Source Code

Here is the source code of the Java Program to Find the Union and Intersection of 2 Arrays. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

advertisement
  1.  
  2. // Java Program to Find the Union and Intersection of 2 Arrays.
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Arrays;
  8. import java.util.HashSet;
  9. import java.util.Set;
  10.  
  11. public class UnionAndIntersection {
  12.     // Function to find and display the union and intersection
  13.     static void displayUnionAndIntersection(int[] arrayOne,int[] arrayTwo){
  14.         Set<Integer> obj = new HashSet<>();
  15.         int i,j;
  16.         for(i=0; i<arrayOne.length; i++){
  17.             obj.add(arrayOne[i]);
  18.         }
  19.         for(j=0; j<arrayTwo.length; j++){
  20.             obj.add(arrayTwo[j]);
  21.         }
  22.         System.out.println("The union of both the arrays is");
  23.         for(Integer I: obj){
  24.             System.out.print(I + " ");
  25.         }
  26.         System.out.println();
  27.         obj.clear();
  28.         System.out.println("The intersection of both the arrays is");
  29.         for(i=0; i<arrayOne.length; i++){
  30.             obj.add(arrayOne[i]);
  31.         }
  32.         for(j=0; j<arrayTwo.length; j++){
  33.             if(obj.contains(arrayTwo[j]))
  34.                 System.out.print(arrayTwo[j] + " ");
  35.         }
  36.     }
  37.     // Function to read the input
  38.     public static void main(String[] args) {
  39.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  40.         int m,n;
  41.         System.out.println("Enter the size of the two arrays");
  42.         try {
  43.             n = Integer.parseInt(br.readLine());
  44.             m = Integer.parseInt(br.readLine());
  45.         }
  46.         catch (IOException e)
  47.         {
  48.             System.out.println("Invalid input");
  49.             return;
  50.         }
  51.         int[] arrayOne = new int[n];
  52.         int[] arrayTwo = new int[m];
  53.         System.out.println("Enter the first array elements");
  54.         int i,j;
  55.         for(i=0; i<arrayOne.length; i++){
  56.             try {
  57.                 arrayOne[i] = Integer.parseInt(br.readLine());
  58.             }
  59.             catch (IOException e)
  60.             {
  61.                 System.out.println("Invalid array element. Enter it again");
  62.                 i--;
  63.             }
  64.         }
  65.         System.out.println("Enter the second array elements");
  66.         for(i=0; i<arrayTwo.length; i++){
  67.             try {
  68.                 arrayTwo[i] = Integer.parseInt(br.readLine());
  69.             }
  70.             catch (IOException e)
  71.             {
  72.                 System.out.println("Invalid array element. Enter it again");
  73.                 i--;
  74.             }
  75.         }
  76.         displayUnionAndIntersection(arrayOne,arrayTwo);
  77.     }
  78. }
Program Explanation

1. In function displayUnionAndIntersection(), a hash set object is created, which follows all the properties of a set.
2. The loops for(j=0; j<arrayTwo.length; j++) and for(i=0; i<arrayOne.length; i++) adds the elements of the two arrays to the HashSet. An element if already present in the HashSet is not added automatically.
3. The loop for(Integer I: obj) is a for-each loop and it displays the union of the two arrays. Next, the HashSet is cleared.
4. Now the elements of the arrayOne are again added to the HashSet.
5. The last loop for(j=0; j<arrayTwo.length; j++) displays the intersection of the two arrays.

Time Complexity: O(n + m) where n is the number of elements in the first array and m is the number of elements in the second array.

Runtime Test Cases
advertisement
 
 
Case 1 (Simple Test Case):
 
Enter the size of the two arrays
5
5
Enter the first array elements
1
2
3
4
5
Enter the second array elements
5
3
6
7
9
The union of both the arrays is
1 2 3 4 5 6 7 9 
The intersection of both the arrays is
5 3 
 
Case 2 (Simple Test Case - entirely different arrays):
 
Enter the size of the two arrays
4
4
Enter the first array elements
1
2
3
4
Enter the second array elements
6
7
8
9
The union of both the arrays is
1 2 3 4 6 7 8 9 
The intersection of both the arrays is
 
 
Case 3 (Simple Test Case - entirely same arrays):
 
Enter the size of the two arrays
4
4
Enter the first array elements
1
2
3
4
Enter the second array elements
1
2
3
4
The union of both the arrays is
1 2 3 4 
The intersection of both the arrays is
1 2 3 4

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.