How to remove duplicate elements from ArrayList in Java

How to remove duplicate elements from ArrayList in Java


Many times we need to remove duplicate or repetitive elements from the ArrayList because ArrayList dont check for duplicates. We will use HashSet to remove duplicates from the ArrayList. As we all know HashSet do not store duplicates but it also do not maintain the order of insertion. So we need to keep it in mind while using HashSet to remove duplicates from the arraylist in java. Following example shows to delete duplicates from ArrayList

Java program to delete duplicates from ArrayList using HashSet




 
public static void removeDuplicates(ArrayList arList)
{
Set set = new HashSet();
List tempList = new ArrayList();
for (Iterator iter = arList.iterator(); iter.hasNext(); ) {
Object element = iter.next();
if ( set.add(element) ) { //Condition to check duplicates
tempList.add( element ); //Adding non duplicate elements
}
arList.clear(); //Clearing old contents
arList.addAll( tempList ); //Adding list without duplicates
}
}

In above example in order to maintain the sorting order of the arrayalist we are first adding the element to the hashset if element doesnt get added we are not adding it to arraylist.
I would like to add one more method for removing duplicates from arraylist. In this method we will be using LinkedHashSet instead of HashSet because LinkedHashSet maintains the order of the ArrayList while removing duplicate elements from ArrayList

Java program to delete duplicates from ArrayList using LinkedHashSet



 
LinkedHashSet linkedHashSet = new LinkedHashSet( arList );
List arListWithoutDuplicates = new ArrayList( linkedHashSet );


In above example we are creating first LinkedHashSet from the ArrrayList which has duplicates, LinkedHashSet removes the duplicates and maintain the same order as the ArrayList. Once we get the LinkedHashSet we will get the new ArrayList from the LinkedHashSet which do not contain the duplicates and order remains same as previous one.

So we have just looked at two methods to remove the duplicate or repetitive elements from ArrayList one is using HashSet and other is using LinkedHashSet.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment