Finding the union of two arrays.
Here’s an example of a Java program that finds the union of two arrays:
import java.util.HashSet; public class ArrayUnion { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {4, 5, 6, 7, 8}; int[] union = findUnion(array1, array2); System.out.print("Union of the arrays: "); for (int num : union) { System.out.print(num + " "); } } public static int[] findUnion(int[] array1, int[] array2) { // Create a HashSet to store unique elements from both arrays HashSet<Integer> unionSet = new HashSet<>(); // Add elements from the first array for (int num : array1) { unionSet.add(num); } // Add elements from the second array for (int num : array2) { unionSet.add(num); } // Convert the unionSet back to an array int[] unionArray = new int[unionSet.size()]; int index = 0; for (int num : unionSet) { unionArray[index++] = num; } return unionArray; } }
In this program, we have a `findUnion` method that takes two arrays as input parameters. It uses a `HashSet` to store unique elements from both arrays. It iterates over each element in both arrays and adds them to the `HashSet`. Finally, it converts the `HashSet` back to an array and returns the resulting union.
In the `main` method, we define two example arrays (`array1` and `array2`). We call the `findUnion` method with these arrays and store the result in the `union` array. Then, we simply print the elements of the `union` array to display the union of the two input arrays.
No comments yet! You be the first to comment.