How to Find Common Elements Between Two Lists in Java 8

Learn how to Find Common Elements Between Two Lists in Java 8 using the Stream API . By combining the stream(), filter(), and collect() methods, we can efficiently identify elements that exist in both collections.

Code Explanation (Step-by-Step)

  • Create two lists using Arrays.asList().
  • Convert list1 into a stream using stream() .
  • Use filter(list2::contains) to check whether each element of list1 exists in list2.
  • Only common elements pass through the filter.
  • Use collect(Collectors.toList()) to store the common elements in a new list.
  • Print the common elements into a new list.
				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CommonElements {
    public static void main(String[] args) {

        List<Integer> list1 = Arrays.asList(23, 45, 67, 80, 21, 98);
        List<Integer> list2 = Arrays.asList(12, 67, 43, 78, 80, 23);

        List<Integer> commonElement = list1.stream()
                                           .filter(list2::contains)
                                           .collect(Collectors.toList());

        System.out.println("Common elements are :- " + commonElement);
    }
}
				
			

Output :
Common elements are :- [23, 67, 80]

HashSet Optimization for Finding Common Elements Between Two Lists in Java 8

				
					import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CommonElements {
    public static void main(String[] args) {

        List<Integer> list1 = Arrays.asList(23, 45, 67, 80, 21, 98);
        List<Integer> list2 = Arrays.asList(12, 67, 43, 78, 80, 23);

        Set<Integer> set = new HashSet<Integer>(list2);

        List<Integer> commonElements = list1.stream()
                                            .filter(set::contains)
                                            .collect(Collectors.toList());

        System.out.println("Common Elements: " + commonElements);
    }
}
				
			

FAQ
Which Java 8 Stream methods are used to find common elements?
Commonly used methods are: stream(), filter(), distinct(), collect(), Collectors.toList()
Is the original list modified when using Stream API?
No. Stream operations do not modify the original lists. They create a new result based on the stream operations.
Which best approach is recommended?
The most recommended approaches are:
• filter(list2::contains) using Stream API
• HashSet + Stream API for optimized performance
• retainAll() for a Collections Framework approach
What does list2::contains mean?
It is a method reference that calls the contains() method of list2.
.filter(element -> list2.contains(element))
Can I find the intersection without using Streams?
Yes, using retainAll():
List<Integer> result = new ArrayList<>(list1);
result.retainAll(list2);