Intersection provides the common elements between two arrays. Let us find the intersection between two arrays in java.
It has two types
- 1. Using HashSet
- 2. Using Sorted Arrays
Both of the methods are implemented as follows.
1.Using HashSet
This
method implementation uses HashSet objects.
- A public class is created with main() function.
- HashSet objects set1, is1 are created.
- Two arrays are created in the main() function and passed to findIt() function.
- ‘findIt()’ reads the arrays and store it to set1.
- Check the the second array elements with set1. If both are equal, it is stored in is1.
- Other wise, the loop is moving to next element.
- Finally, the result is displayed.
Program:
import java.util.HashSet;
import java.util.Set;
public class ArrayIsEg {
public static void
findIt(int[] a1, int[] a2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> is1 = new HashSet<>();
// Let us
insert elements of first array to the set
for (int no :
a1) {
set1.add(no);
}
// let us find
if there is any common elements
for (int no :
a2) {
if
(set1.contains(no)) {
is1.add(no);
}
}
// The common
elements are displayed here
System.out.println("Intersection of Arrays: " + is1);
}
public static void
main(String[] args) {
int[] a1 =
{11, 22, 33, 44, 55};
int[] a2 =
{44, 55, 16, 77};
findIt(a1,
a2);
}
}
Output:
C:\raji\blog>javac ArrayIsEg.java
C:\raji\blog>java ArrayIsEg
Intersection of Arrays: [55, 44]
2.Using Sorted Arrays
This
method reads two arrays as input and pass it to ‘findIt()’ method.
- ‘findIt()’ method sorts both of array.
- Both of the arrays are compared, if any common elements are there, it prints the element.
- Otherwise, it moves to next element.
Program:
import java.util.Arrays;
public class SortedArrayIs {
public static void
findIt(int[] a1, int[] a2) {
Arrays.sort(a1);
Arrays.sort(a2);
int i = 0, j =
0;
System.out.print("Intersection of Arrays: ");
while (i <
a1.length && j < a2.length) {
if (a1[i]
== a2[j]) {
System.out.print(a1[i] + " ");
i++;
j++;
} else if
(a1[i] < a2[j]) {
i++;
} else {
j++;
}
}
}
public static void
main(String[] args) {
int[] a1 =
{11, 21, 31, 41, 51};
int[] a2 =
{31, 41, 51, 61, 71};
findIt(a1,
a2);
}
}
Output:
C:\raji\blog>javac SortedArrayIs.java
C:\raji\blog>java SortedArrayIs
Intersection of Arrays: 31 41 51
This is the way of implementing the intersection of two arrays in java. Hope, this code is useful to you. Keep Coding!!!
No comments:
Post a Comment