List Intersection in Java: Explanation & Practice
Find common elements between two lists
Problem summary
Write a program that finds all elements that appear in both lists.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8); // Test case 1
// Find common elements
// Print space-separated
}
}Expected output and test cases
- Common: 4 and 5
4 5
- More overlap
2 3 4
- No common elements
Hints
- Convert to HashSet for O(1) lookup
- Use retainAll() for intersection
- Or iterate and check contains()
Related Collections exercises
- Practice Word Frequency Counter in Java
- Practice Remove Duplicates from List in Java
- Practice Sort Map by Value in Java
Practice all Collections exercises · Run this idea in the Java compiler