Given two arrays, find the common elements in them.
Example: [1,45,33,23,22,45,233,21], [5,23,45,0,9,23,1,9]
=> Output: [1,45, 23]
import java.io.*;
import java.util.*;
class Mycode {
public static void main(String args[]) {
int a[] = {1, 45, 33, 23, 22, 45, 233, 21};
int b[] = {5, 23, 45, 0, 9, 45, 1, 9};
Mycode test = new Mycode();
test.testNumber(a, b);
}
void testNumber(int c[], int d[]) {
System.out.println(Arrays.toString(c));
System.out.println(Arrays.toString(d));
Set<Integer> hset = new HashSet<Integer>();
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
System.out.println(c[i]);
hset.add(c[i]);
}
}
}
System.out.println(hset);
}
}
Actual Output: [1, 45, 33, 23, 22, 4, 233, 21] [5, 23, 45, 0, 9, 5, 1, 9]
=>
[1, 23, 45]