1. Introduction
Finding the union of two arrays involves determining the set of distinct elements from both arrays. In Java, this can be achieved by utilizing Set collections, which inherently do not allow duplicate elements. This tutorial demonstrates a technique for finding the union of two arrays in Java.
2. Program Steps
1. Initialize two arrays with elements.
2. Convert both arrays to Set objects.
3. Use the addAll method on one of the sets, passing the other set as a parameter, to perform the union.
4. Convert the resultant set back to an array.
5. Display the union array.
3. Code Program
import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
public class ArrayUnion {
public static void main(String[] args) {
// Step 1: Initialize two arrays with elements
Integer[] array1 = {1, 2, 3, 4, 5};
Integer[] array2 = {4, 5, 6, 7, 8};
// Step 2: Convert the arrays to Set objects
Set<Integer> set1 = new HashSet<>(Arrays.asList(array1));
Set<Integer> set2 = new HashSet<>(Arrays.asList(array2));
// Step 3: Use addAll method to find the union of set1 and set2
set1.addAll(set2);
// Step 4: Convert the resultant set back to an array
Integer[] unionArray = set1.toArray(new Integer[0]);
// Step 5: Display the union array
System.out.println("Union of the two arrays: " + Arrays.toString(unionArray));
}
}
Output:
Union of the two arrays: [1, 2, 3, 4, 5, 6, 7, 8]
4. Step By Step Explanation
Step 1: We begin by initializing two Integer arrays array1 and array2 with some elements.
Step 2: Next, we convert array1 and array2 to Set objects set1 and set2 respectively, utilizing the Arrays.asList(array) method.
Step 3: The addAll method is employed on set1, with set2 passed as the parameter, to perform the union operation. This method adds all the elements of set2 to set1, ensuring no duplicates.
Step 4: The resultant set1, now containing the union of the elements, is converted back to an array named unionArray through the toArray method.
Step 5: Finally, we print out the unionArray using the Arrays.toString() method, showcasing the distinct elements present in array1 and array2.