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
Really nice blog,i enjoyed your infomations. Thank you and i will expect more in future.
ReplyDeleteJAVA Training in Chennai
Best JAVA Training institute in Chennai
Python Training in Chennai
Selenium Training in Chennai
Android Training in Chennai
Big data training in chennai
JAVA Training in Annanagar
java training in chennai anna nagar
why this program shows error in my pc
ReplyDeletePlease share your error
DeleteThanks for share such a valuable information. your content is very helpful for us. keep shearing these type of new ideas thanks.
ReplyDeleteAndroid Training Institute in Chennai | Android Training Institute in anna nagar | Android Training Institute in omr | Android Training Institute in porur | Android Training Institute in tambaram | Android Training Institute in velachery