Thursday, 14 July 2016

Java Code Showing use of Comparator Interface

class School {
private String name;
private int rollNo;
public School(String name,int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
@Override
public String toString() {
return "Name : "+name+"\t"+"Roll No : "+rollNo;
}
}
class SortByRollNo implements Comparator<School>{
@Override
public int compare(School s1, School s2) {
return (s1.getRollNo() < s2.getRollNo() ? -1 : (s1.getRollNo() > s2.getRollNo()) ? 1 : 0);
}
}
class SortByName implements Comparator<School>{
@Override
public int compare(School s1, School s2) {
return s1.getName().compareTo(s2.getName());
}
}
public class ComparatorExample {

public static void main(String[] args) {
School s=new School("Pushkar",104);
School s1=new School("Alok",101);
School s2=new School("Sanjay",102);
School s3=new School("Zimmy",103);
List<School> list = new ArrayList<School>();
list.add(s);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("SORTING BY ROLL NO : \n");
Collections.sort(list,new SortByRollNo());
Iterator<School> ir = list.iterator();
School sc = null;
while(ir.hasNext()){
sc = ir.next();
System.out.println(sc);
}
System.out.println("SORTING BY NAME : \n");
Collections.sort(list,new SortByName());
Iterator<School> ir1 = list.iterator();
School sc1 = null;
while(ir1.hasNext()){
sc1 = ir1.next();
System.out.println(sc1);
}
}

}

No comments:

Post a Comment