Remove duplicates from a list and keep the order

Description: Remove the duplicates from [4, 7, 4, 1, 7, 9, 1] and keep the order of the first appearance.

Hint:

  • A LinkedHashSet keeps the insert order. Or use stream().distinct().

Solution

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(4, 7, 4, 1, 7, 9, 1);

        List<Integer> a = new ArrayList<>(new LinkedHashSet<>(numbers));
        List<Integer> b = numbers.stream().distinct().toList();

        System.out.println(a);
        System.out.println(b);
    }
}
Output

[4, 7, 1, 9]
[4, 7, 1, 9]

How it works

  • A set does not allow duplicates, and the linked version remembers the order.

Read HashSet and LinkedList.


Learn more about the similar topics:
Tutorials
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?