How to Remove Duplicate Elements from ArrayList in Java

In this tutorial you will learn how to remove duplicate elements from arraylist in Java.

We can remove repeated elements in arraylist by two ways.

  • Using HashSet – Do not maintain the insertion order.
  • Using LinkedHashSet – Maintain the insertion order.

 

First we create an ArrayList and add some duplicate elements to it.

Now copy elements of ArrayList to HashSet or LinkedHashSet.

Remove all elements of ArrayList by clear() method.

Finally copy elements of HashSet or LinkedHashSet back to the ArrayList.

Below example shows how to implement this.

 

How to Remove Duplicate Elements from ArrayList in Java

 

Output

How to Remove Duplicate Elements from ArrayList in Java

You can observe the output. In case of HashSet, the insertion order is not maintained while in LinkedHashSet the insertion order is maintained.

Comment below if have any doubts regarding above tutorial.

1 thought on “How to Remove Duplicate Elements from ArrayList in Java”

Leave a Comment

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