How to remove duplicate values from java list/arraylist?(java 7 and java 8)

What if you get some duplicate records in a List ?

So we will see how to remove duplicate objects from List or ArrayList collection.


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

public class remduplicatesfromlist {

 public static void main(String args[]) {

 List<String> l1 = new ArrayList<String>();
 // add duplicates

 // prints out without the order of insertion. 
 List<String> list2 = new ArrayList<>(new HashSet<>(l1));

 // prints out with the order of insertion. 
 List<String> list3 = new ArrayList<>(new LinkedHashSet<>(l1));
 Iterator<String> itr = list2.iterator();
 Iterator<String> itr1 = list3.iterator();
 while (itr.hasNext()) {
 System.out.println("Print list2:";
 while (itr1.hasNext()) {
 System.out.println("Print list3:";



Print list2:banana
Print list2:orange
Print list2:apple
Print list3:apple
Print list3:banana
Print list3:orange

Behind the scenes this what happens

  • print without duplicate, not in order

Set setList= new HashSet(l1);
List list2= new ArrayList(setList);

  • print without duplicate, in order

Set setList = new LinkedHashSet<>(l1);
List list3 = new ArrayList<>(setList);

In Java 8, it is one liner to get a list without duplicates and in order.

 l1 =;

Note: The distinct() method from the Stream API which returns a stream consisting of the distinct elements based on the result returned by equals() method.

Hope this helps you to understand how to remove duplicates in a list.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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