Skip to content

Remove duplicate values from a List in Java

In this article, we will learn how to remove duplicate elements from a list in Java. Below are the some of the solutions.

Plain Java

We can use Set in Collection framework, so we all know that Set doesn’t allow the duplicate elements.
Note: Use HashSet to get Ordered List. To maintain the original order of the list use LinkedHashSet.

// List of elements with duplicate
List<Integer> listWithDupli = new ArrayList(Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
// Using HashSet
List<Integer> listWithoutDupli = new ArrayList<>(new HashSet<>(listWithDuplicates));
// Ouput: [1, 2, 3, 4, 5, 10]
// Using LinkedHashSet
List<Integer> orderlistWithoutDupli = new ArrayList<>(new LinkedHashSet<>(listWithDuplicates));
// Output: [1, 10, 2, 3, 4, 5]

Java 8 Stream

We can use Stream.distinct() method from the Stream API. This will return the ordered list without duplicate elements.

// List of elements with duplicate
List<Integer> listWithDupli = new ArrayList(Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
List<Integer> listWithoutDupli = listWithDuplicates.stream().distinct().collect(Collectors.toList());
// Output: [1, 2, 3, 4, 5, 10]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.