Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday, 27 April 2016

Remove duplicate element in Arraylist using Comparator


package samset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class RemoveDuplicateElement {

public static void main(String[] args) {

final ArrayList emp = new ArrayList();
emp.add(new Employee("emp1", "001"));
emp.add(new Employee("emp2", "002"));
emp.add(new Employee("emp3", "003"));
emp.add(new Employee("emp4", "004"));
emp.add(new Employee("emp5", "001"));
emp.add(new Employee("emp6", "004"));

// Before using comprator
System.out.println(emp);

Set set = new TreeSet(new Comparator() {
@Override
public int compare(Employee o1, Employee o2) {
if(o1.getId().equalsIgnoreCase(o2.getId())){
        return 0;
        }
        return 1;
}
});
set.addAll(emp);

System.out.println(" After using comparator removing duplicates ");

    final ArrayList newList = new ArrayList(set);

    // Print original list 
System.out.println(newList);
}

}

class Employee {
private String name;
private String id;

public Employee(String name, String id) {
this.name = name;
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Override
public String toString() {
return "\n" +"Name=" + name + "   Id=" + id ;
}

}


Output :-

[
Name= Employee 1   Id=001, 
Name= Employee 2   Id=002, 
Name= Employee 3   Id=003, 
Name= Employee 4   Id=004, 
Name= Employee 5   Id=001, 
Name= Employee 6   Id=004]

<<<<< After using compartor >>>>>>

[
Name= Employee 1   Id=001, 
Name= Employee 2   Id=002, 
Name= Employee 3   Id=003, 
Name= Employee 4   Id=004]


Thank you