Finding common elements between 2 lists
suggest changeSuppose you have two lists: A and B, and you need to find the elements that exist in both lists.
List.retainAll keeps only the receiver's elements that are also in the argument, and it modifies that receiver. The example copies numbersA first so the original lists stay intact. retainAll uses equals.
Example:
public static void main(String[] args) {
List<Integer> numbersA = new ArrayList<>();
List<Integer> numbersB = new ArrayList<>();
numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 }));
numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 }));
System.out.println("A: " + numbersA);
System.out.println("B: " + numbersB);
List<Integer> numbersC = new ArrayList<>();
numbersC.addAll(numbersA);
numbersC.retainAll(numbersB);
System.out.println("List A : " + numbersA);
System.out.println("List B : " + numbersB);
System.out.println("Common elements between A and B: " + numbersC);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents