How to get union between two arrays

Learn to find the union between two arrays in Java using HashSet class. In set theory, the union (denoted by U) of a collection of sets is the set of all elements in the collection.

For example, the union of two sets A and B is the set of all the elements which are either in A, or in B, or in both A and B.

Union
Union

To get the union of two arrays, follow these steps:

  1. Push first array in a HashSet instance.
  2. Use addAll() method to add the elements of the second array into set.
  3. Similarly, add all the elements of more arrays in the set, if any.

1. Union between two integer arrays

Java program to get the union between two integer arrays and print the output.

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

public class Main 
{
  public static void main(String[] args) 
  {
    Integer[] firstArray = {0,2,4,6,8};
      Integer[] secondArray = {1,3,5,7,9};
      
      HashSet<Integer> set = new HashSet<>(); 
      
      set.addAll(Arrays.asList(firstArray));
      
      set.addAll(Arrays.asList(secondArray));
      
      System.out.println(set);
    
    //convert to array
      Integer[] union = {};
    union = set.toArray(union);
    
    System.out.println(Arrays.toString(union));
  }
}

Program output.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Union between two string arrays

Java program to get the union between two string arrays and print the output.

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

public class Main 
{
  public static void main(String[] args) 
  {
    String[] firstArray = {"A", "B", "C", "D"};
    String[] secondArray = {"D", "A", "E", "F"};
    
    HashSet<String> set = new HashSet<>(); 
    
    set.addAll(Arrays.asList(firstArray));
    
    set.addAll(Arrays.asList(secondArray));
    
    System.out.println(set);
    
    //convert to array
    String[] union = {};
    union = set.toArray(union);
    
    System.out.println(Arrays.toString(union));
  }
}

Program output.

[A, B, C, D, E, F]
[A, B, C, D, E, F]

Happy Learning !!

Read More : How to get intersection between two arrays

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.