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

  1. Convert to HashSet for O(1) lookup
  2. Use retainAll() for intersection
  3. Or iterate and check contains()

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler