Skip to content

Java LinkedList Remove Duplicate Elements Example

This example shows how to remove duplicate elements from the LinkedList in Java. This example also shows how to remove duplicates using the HashSet and LinkedHashSet classes.

How to remove duplicate elements from the LinkedList in Java?

The LinkedList class is a Java linked list implementation of the List interface. The LinkedList class does not prevent us from adding duplicate elements to it.

However, if you want to remove duplicate elements from the LinkedList object, you can do that in a couple of ways.

1. Using the HashSet or LinkedHashSet class

The Java HashSet class is a Set implementation and does not allow duplicate elements. We can use this property of the Set to remove duplicate elements from the LinkedList as given below.

Output

As you can see from the output, all the duplicate elements from the LinkedList were not added to the HashSet object.

However, if you look closely, the order of the elements is different from the original. That is because the HashSet class does not guarantee to maintain the insertion order of its elements.

If you want to retain the order of the elements of the LinkedList, use the LinkedHashSet class instead of the HashSet class as given below.

Output

As you can see from the output, now the order of the elements in the LinkedList object is the same as before.

2. Using the Stream (Java 8 and above)

If you are using Java 8 or later version, you use the stream to remove duplicates from the linked list as given below.

Output

How to remove duplicate objects of a custom class from the LinkedList?

The above examples use the Integer class as the linked list elements. The Integer class has implemented the equals method. That is the reason the above examples worked.

If the equals method is not implemented in the custom class, then the equals method from the Object class will be used which compares only object references not the actual objects. If the LinkedList object contains the custom class objects, then the custom class must implement the equals and hashCode methods to work.

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

Leave a Reply

Your email address will not be published.