Finding the common elements in two arrays.
Here’s a Java program that finds the common elements in two arrays:
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class CommonElementsInArrays { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {4, 5, 6, 7, 8}; int[] commonElements = findCommonElements(array1, array2); System.out.println("Common elements:"); for (int element : commonElements) { System.out.print(element + " "); } } public static int[] findCommonElements(int[] array1, int[] array2) { Set<Integer> set1 = new HashSet<>(); for (int element : array1) { set1.add(element); } List<Integer> commonElementsList = new ArrayList<>(); for (int element : array2) { if (set1.contains(element)) { commonElementsList.add(element); } } int[] commonElementsArray = new int[commonElementsList.size()]; for (int i = 0; i < commonElementsList.size(); i++) { commonElementsArray[i] = commonElementsList.get(i); } return commonElementsArray; } }
This program defines a `findCommonElements` method that takes two arrays as input and returns an array containing the common elements between the two input arrays. It uses a `HashSet` to store the elements of the first array for efficient lookup, and then iterates through the second array to check for common elements. The common elements are stored in an `ArrayList` and finally converted to an array before being returned.
In the `main` method, we provide sample input arrays `array1` and `array2`, and then call the `findCommonElements` method to find the common elements. The common elements are then printed to the console. In this example, the output will be `4 5`, as these are the elements common to both arrays.