Remove Duplicates from a List in Java

In this post, we will see how to remove duplicates from a List in Java without destroying the original ordering of the elements in the List.


 

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 will get a set of elements from the list but without any duplicates. Now if we convert the set back to a list, we will get a list without any duplicates.

Please note that the ordering of the elements will be destroyed if an ArrayList is used. To preserve the original order, we can use TreeSet or LinkedHashset instead.

Download   Run Code

Output:

[C++, Java]

 

2. Java 8 Streams

Here’s how this can be done in Java 8 using Stream API:

Download   Run Code

Output:

[Java, C++]

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

Download   Run Code

Output:

[C++, Java]

 

3. 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   Run Code

Output:

[Java, C++]

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

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

Download   Run Code

Output:

[C++, Java]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz