Collections(Java)-Comparator example program
Employees.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Employees {
String name;
int id;
//setters
public void setName(String name){
this.name=name;
}
public void setId(int id){
this.id=id;
}
//getters
public String getName(){
return name;
}
public int getId(){
return id;
}
//constructor
public Employees(String name,int id){
this.name=name;
this.id=id;
}
public static void main(String [] args){
Employees e1=new Employees("xyz",37);
Employees e2=new Employees("abc",38);
Employees e3=new Employees("sst",39);
ArrayList<Employees> arrayList=new ArrayList<Employees>();
arrayList.add(e1);
arrayList.add(e2);
arrayList.add(e3);
Collections.sort(arrayList,new EmployeesSortByName());
Iterator<Employees> itr=arrayList.iterator();
while(itr.hasNext()){
Employees em=(Employees)itr.next();
System.out.println(em.getName()+" "+em.getId());
}
}
}
EmployeesSortByName.java
import java.util.Comparator;
public class EmployeesSortByName implements Comparator<Employees> {
@Override
public int compare(Employees arg1, Employees arg2) {
// TODO Auto-generated method stub
return arg1.getName().compareTo(arg2.getName());
}
}
Output:
abc 38
sst 39
xyz 37
Comments
Post a Comment