Java Streams: Find Common Elements in Two Lists

🚀 Day 3 of Java Series 👉 Find common elements between two lists using Streams import java.util.*; import java.util.stream.*; public class CommonElementsExample { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30, 40, 50); List<Integer> list2 = List.of(30, 40, 60, 70); Set<Integer> set2 = new HashSet<>(list2); List<Integer> common = list1.stream() .filter(set2::contains) .toList(); System.out.println(common); // [30, 40] } } 💡 What’s happening here? ✔ Convert one list into a HashSet → O(1) lookup ✔ Stream through list1 ✔ Filter only elements present in list2 ✔ Collect result into a list ⚡ Key Insight: Using List.contains() leads to O(n²) complexity Using HashSet reduces it to O(n + m) 🧠 Interview Tip: Always optimize lookups using HashSet when dealing with search operations 📌 Output: [30, 40] ❓Can you think of a way to handle duplicates in both lists? #Java #Streams #CodingInterview #Developers #JavaDeveloper #Learning #Tech

Output will be [30,40,50]

Like
Reply

To view or add a comment, sign in

Explore content categories