This post will discuss how to remove duplicates from a list in Java without destroying the original ordering of the list elements.

1. Plain Java

We know that a set doesn’t allow any duplicate elements. So if we convert the given list with duplicates to a set, we’ll get a set of elements from the list without duplicates. If we convert the set back to a list, we’ll get a list without duplicates.

Please note that HashSet will destroy the ordering of the elements. To preserve the original order, we can use LinkedHashset instead.

Download  Run Code

Output:

[C++, Java]

2. Using Java 8 Stream

Here’s how we can do this in Java 8 and above using Stream:

Download  Run Code

Output:

[Java, C++]

 
The above approach destroys the ordering of the list elements. To preserve the original order, we can use Stream.distinct(), as shown below:

Download  Run Code

Output:

[C++, Java]

 
This is equivalent to:

Download  Run Code

Output:

[C++, Java]

3. Using Guava Library

Guava also provides static methods to create mutable instances of List and Set. These can be used with Java 7 or before to remove duplicates from a list.

Download Code

Output:

[Java, C++]

 
If mutability is not required, we can go for immutable lists:

 
The above approach also destroys the ordering of the list elements. To preserve the original order, we can use ImmutableSet.copyOf(), as shown below:

Download Code

Output:

[C++, Java]

That’s all about removing duplicates from a List in Java.