This post will discuss how to find the common elements in two lists in Java.

1. Using Collection.retainAll() method

The recommended approach to remove elements from a collection that are missing in the other collection is using the retainAll() method, which retains only the elements in the collection that are contained in the specified collection.

You can use the retainAll() method as follows to find all common elements. The following solution transforms the first list into a Set, and call retainAll on it. This is done to avoid modifying the original list.

Download  Run Code

Output:

[3, 5]

2. Using Stream API

Stream API made it very convenient to filter a collection. The idea is to get a stream of the elements in the first collection and filter elements that are contained in the other collection. This can be easily done using the List.contains() method.

Download  Run Code

Output:

[3, 5]

 
You can improve efficiency by converting the second collection to a HashSet and calling its contains() method.

Download  Run Code

Output:

[3, 5]

3. Using Apache Commons Collections

You can also use CollectionUtils.intersection() provided by Apache Commons Collections to get the intersection between the given iterables. Once you have the Collection containing the intersection of the two collections, you can optionally transform it into a Set or a List.

Download Code

Output:

[3, 5]

4. Using Guava

Similar to the Apache Commons Collections library, Guava offers the Sets.intersection() method, which returns an unmodifiable view of the intersection of two sets. It can be used as follows:

Download Code

Output:

[3, 5]

That’s all about finding the common elements in two lists in Java.