{{theTime}}

Search This Blog

Total Pageviews

Java Comparator Example to sort students by rank

A comparator is a comparison function used to compare objects and sort objects.
Example: Sort students based on students rank.


class Student {
String name ;
long rank ;

public Student(String name, long rank){
this.name = name ;
this.rank = rank ;
}
public long getRank() {
return rank ;
}

public static void main(String[] str){
Student stu1 = new Student("John", 20) ;
Student stu2 = new Student("Paul", 3) ;
Student stu3 = new Student("Ponit", 1) ;
Vector studentVector =new Vector() ;
studentVector.add(stu1) ;
studentVector.add(stu2) ;
studentVector.add(stu3) ;
Collections.sort(studentVector, new StudentRankComparator()) ;
}
}
class StudentRankComparator implements Comparator {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;

@Override
public int compare(Student stuFirst, Student stuSec)
{
double qtyFirst = stuFirst.getRank() ;
double qtySec = stuSec.getRank() ;
if( qtyFirst > qtySec){
return AFTER ;
}else if(qtyFirst return BEFORE ;
}
return EQUAL;
}
}

No comments:

Java Sequenced Collection Java Sequenced Collection The Sequenced Collection feature was introduced in Jav...