Finding common elements between 2 lists

suggest change

Suppose 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);

}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents