List Intersection in Java: Solution, 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()

Validated solution

Reveal Java solution
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<Integer> first = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Set<Integer> second = new HashSet<>(Arrays.asList(4, 5, 6, 7));
        first.retainAll(second);
        first.stream().sorted().forEach(value -> System.out.print(value + " "));
    }
}

How to approach the problem

Set intersection keeps values that appear in both collections. retainAll mutates the receiving set, so make a copy when the original set must remain available.

Approach

  1. Build a membership set.
  2. Intersect it with the other collection.
  3. Sort only because the displayed output needs a stable order.

Time and space complexity

Time: O(n + m) expected, plus sorting output. Space: O(n + m).

Edge cases to test

  • No overlap produces an empty result.
  • A set intentionally removes duplicate multiplicities.

Common mistakes

  • Calling retainAll on a collection that must be preserved.
  • Expecting duplicate values to appear multiple times in a set intersection.

Follow-up challenge

Compute a multiset intersection that preserves duplicate counts.

Related Collections exercises

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