How to Remove Duplicates from ArrayList in Java

Remove Duplicates from ArrayList
Remove Duplicates from ArrayList
We use ArrayList a lot but what if we want to remove duplicates from ArrayList with an easy method.There are other cumbersome ways to do this by iterating through ArrayList and removing etc, but here i will use another easy way to remove repeated values in ArrayList, that is by using another collection called Set. Set is a collection which does not allow insertion of duplicate values in to it.So under Set Collection there are two candidates which can do this job they are HashSet and LinkedHashSet. HashSet does not retain order of elements inserted to it while LinkedHashSet preserve the order, so you can use either of the one based on your situation, here i will use LinkedHashSet so i can preserve the order of elements as same as its seen in my ArrayList.

So the steps to do that are

1.Copy all the elements in our duplicated ArrayList to a LinkedHashSet. 
2.Now clear all the values in our duplicated ArrayList and fill it back with non duplicated values from LinkedHashSet.

Code in Action below!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
List<String> arrayListObject = new ArrayList<>();
// adding elements to arrayListObject, including duplicates,Total 5 elements
arrayListObject.add("London");
arrayListObject.add("Paris");
arrayListObject.add("Tokyo");
arrayListObject.add("London");
arrayListObject.add("Paris");
Set<String> hashSetObject = new LinkedHashSet<>();//Note here we use LinkedHashSet
hashSetObject.addAll(arrayListObject);//Adding ArrayList values to LinkedHashSet, duplicates removed
arrayListObject.clear();//Clearing all values in ArrayList
arrayListObject.addAll(hashSetObject);//Filling ArrayList back with non duplicated values, now it has 3 elements


Share on Google Plus

About Vaishakh

I am a Java and Android developer and a science enthusiast.I Like to explain complex things in simple language so anybody even without a graduation in computer science or Electronics can understand the concepts easily.

0 comments:

Post a Comment