How to Remove Duplicates in ArrayList with Example using java code

         Duplicate Elements/Strings can be removed from ArrayList in many ways . One way to remove duplicates will be using HashSet . Because HashSet does not allow duplicates. Just convert the array list to  HashSet and convert back to array list. That is it.

 Another way can be using another ArrayList. Adding elements one by one from the first ArrayList to Second ArrayList by checking whether the element exists in the second array list.

 To find and print duplicates and number of occurrence of duplicates in a file, please visit Find and print duplicates using HashMap 

The below code removes the duplicates from the arraylist in both ways.

import java.util.*;
public class RemoveDuplicates {

public static void main (String[] args)
{


//for using HashSet
ArrayList arrayList1 = new ArrayList();

arrayList1.add("1");
arrayList1.add("2");
arrayList1.add("3");
arrayList1.add("3");
arrayList1.add("1");
arrayList1.add("2");
arrayList1.add("3");


System.out.println("Before Removing Duplicate");

for (Object item : arrayList1)
System.out.println(item);

arrayList1=removeDuplicateUsingHashSet(arrayList1);


System.out.println("After Removing Duplicate in arrayList1 using HashSet");

for (Object item : arrayList1)
System.out.println(item);


//Using Second ArrayList
ArrayList arrayList2 = new ArrayList();

arrayList2.add("Sunday");
arrayList2.add("Monday");
arrayList2.add("Tuesday");
arrayList2.add("Sunday");
arrayList2.add("Wednesday");
arrayList2.add("Tuesday");
arrayList2.add("Thursday");
arrayList2.add("Friday");
arrayList2.add("Monday");
arrayList2.add("Saturday");

System.out.println("Before Removing Duplicate");

for (Object item : arrayList2)
System.out.println(item);


arrayList2=removeDuplicateUsingArrayList(arrayList2);


System.out.println("After Removing Duplicate in arrayList2 using Second ArrayList");

for (Object item : arrayList2)
System.out.println(item);

}
 
     //Using HashSet
public static ArrayList removeDuplicateUsingHashSet(ArrayList a1)
{

HashSet hashSet = new HashSet(a1); //Creating HashSet which does not allows duplicates
a1 = new ArrayList(hashSet) ; //Assigning Hashset back to arraylist1
return a1;
}


//Using another ArrayList
public static ArrayList removeDuplicateUsingArrayList(ArrayList a1)
{
ArrayList a2=new ArrayList();
for (Object item : a1)
{

if (!a2.contains(item)) a2.add(item);

}
return a2;

}

}

Leave a Reply