Remove Duplicates from List in Java: Solution, Explanation & Practice

Remove duplicates while preserving order

Problem summary

Write a program that removes duplicates from a list while maintaining original order.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 3, 2, 1, 4, 2, 3, 5, 4); // Test case 1
        
        // Remove duplicates, preserve order
        // Print space-separated
    }
}

Expected output and test cases

  • Preserve first occurrence order
    1 3 2 4 5
  • Different order
    5 4 3 2 1
  • All same elements
    1

Hints

  1. LinkedHashSet preserves insertion order
  2. Or use ArrayList and check contains()
  3. Convert back to list if needed

Validated solution

Reveal Java solution
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> values = Arrays.asList(1, 3, 2, 3, 1, 4, 5, 2);
        for (int value : new LinkedHashSet<>(values)) System.out.print(value + " ");
    }
}

How to approach the problem

LinkedHashSet combines uniqueness with insertion order. Constructing it from the list retains the first occurrence of each value, then iteration exposes the de-duplicated order.

Approach

  1. Choose LinkedHashSet because order matters.
  2. Construct it from the input list.
  3. Iterate the set or build a new list from it.

Time and space complexity

Time: O(n) expected. Space: O(n).

Edge cases to test

  • An empty list stays empty.
  • Null is a permitted HashSet element but may be inappropriate for the domain.

Common mistakes

  • Using HashSet and losing original order.
  • Removing from an ArrayList during a for-each loop.

Follow-up challenge

Remove duplicates in place from a mutable list with an iterator.

Related Collections exercises

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