Java Program:
Write a program to find common elements between two arrays?
Description:
Write a program to identify common elements or numbers between
two given arrays. You should not use any inbuilt methods are list to
find common values.
Code:
package com.java2novice.algos;
public class CommonElementsInArray {
public static void main(String a[]){
int[] arr1 = {4,7,3,9,2};
int[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j]){
System.out.println(arr1[i]);
}
}
}
}
}
Output:
4
3
9
2
Here's a Java program that finds the common elements between two arrays:
import java.util.HashSet;
import java.util.Scanner;
public class CommonElements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input first array
System.out.print("Enter the size of the first array: ");
int size1 = scanner.nextInt();
int[] array1 = new int[size1];
System.out.println("Enter elements of the first array:");
for (int i = 0; i < size1; i++) {
array1[i] = scanner.nextInt();
}
// Input second array
System.out.print("Enter the size of the second array: ");
int size2 = scanner.nextInt();
int[] array2 = new int[size2];
System.out.println("Enter elements of the second array:");
for (int i = 0; i < size2; i++) {
array2[i] = scanner.nextInt();
}
// Find common elements
HashSet<Integer> commonElements = findCommonElements(array1, array2);
// Display common elements
System.out.println("Common elements between the two arrays: " + commonElements);
scanner.close();
}
public static HashSet<Integer> findCommonElements(int[] array1, int[] array2) {
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> commonSet = new HashSet<>();
// Add elements of the first array to the set
for (int num : array1) {
set1.add(num);
}
// Check for common elements in the second array
for (int num : array2) {
if (set1.contains(num)) {
commonSet.add(num);
}
}
return commonSet;
}
}
Explanation:
Input:
- The program first takes the size and elements of the first array.
- Then it takes the size and elements of the second array.
Finding Common Elements:
- A
HashSet
is used to store elements from the first array. - As the program iterates over the second array, it checks if each element is present in the first array's set.
- If present, it adds that element to the
commonSet
.
- A
Output:
- Finally, the program prints the common elements found in both arrays.
Example:
If you input:
- First array:
[1, 2, 3, 4]
- Second array:
[3, 4, 5, 6]
The output will be:
Common elements between the two arrays: [3, 4]
No comments:
Write comments