Monday, June 18, 2012

Removing Duplicates from List

I came across the follwing cases like :


1. Removing the Duplicate Employees from ArrayList
2. Sorting & Removing the Duplicate Employees from ArrayList


Method 1 :
public static List removeDuplicates(List empList)
{
 Set set = new HashSet(); // Set always returns false in add() mtd if the element existis already in set
 set.addAll(empList);
 empList.clear();
 empList.addAll(set);

 return empList; 
}



Method 2 :
public static List removeDuplicates(List empList)
{
 Set set = new HashSet(empList); // Set always returns false in add() mtd if the element existis already in set 
 empList.clear();
 empList.addAll(set);
 return empList; 
}


Sorting the Employee :
public static List removeDuplicates(List empList)
{
 Set set = new TreeSet(empList); // Set always returns false in add() mtd if the element existis already in set 
 (or)
 Set set = new TreeSet();
 set.addAll(empList);
 
 empList.clear();
 empList.addAll(set);
 return empList; 
}


Please let me know if anybody have the solution for this in OPTIMIZED way.

1 comment: