How to find common elements in two lists with Java Streams

Finding common elements between two lists using Java Streams can be approached with performance in mind. Consider the following two lists: List<Integer> intList1 = List.of(1, 2, 3, 4, 5, 6); List<Integer> intList2 = List.of(2, 4, 6, 8, 10); Here are three options to find the common elements: **Option 1:** ```java System.out.println(intList1.stream() .filter(intList2::contains) .collect(Collectors.toSet())); ``` This method is straightforward but has a time complexity of O(n * m) because for each element in intList1, the `intList2::contains` checks the entire list. This is not efficient for large lists. **Option 2:** ```java Set<Integer> set2 = new HashSet<>(intList2); System.out.println(intList1.stream() .filter(set2::contains) .collect(Collectors.toSet())); ``` In this approach, the time complexity improves to O(n + m) since the average time for a HashSet lookup is O(1). **Option 3:** ```java Set<Integer> common = new HashSet<>(intList1); System.out.println(common.retainAll(intList2)); ``` This option utilizes a built-in function and also achieves a time complexity of O(n + m), while being simpler in implementation. By considering these options, you can choose the most efficient method for your specific use case.

To view or add a comment, sign in

Explore content categories