You can use Stream
API to filter and count the elements in the second list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> second = new ArrayList<>();
first.add(1);
first.add(2);
second.add(2);
second.add(3);
second.add(2);
first.forEach(n -> System.out
.println(n + " exists " + second.stream().filter(e -> e == n).count() + " times in the second list"));
}
}
Output:
1 exists 0 times in the second list
2 exists 2 times in the second list
Alternatively, you can use Collections#frequency
to print the frequency of each number of the list, first
in the list, second
:
for (Integer x : first) {
System.out.println(x + " exists " + Collections.frequency(second, x) + " times in the second list");
}
Alternatively, you can use the nested loops to iterate the list, second
for each number in the list, first
:
for (Integer x : first) {
int count = 0;
for (Integer y : second) {
if (x == y)
count++;
}
System.out.println(x + " exists " + count + " times in the second list");
}