Skip to content
Advertisement

Sort function in Java collections

If I have following list of student objects,

obj1.Name = "ABC";
obj1.Rank = 5;

obj2.Name = "DEF",
obj2.Rank = 3;

obj3.Name = "GHI";
obj3.Rank = 2;

obj4.Name = "JKL";
obj4.Rank = 0;

obj5.Name = "MNO";
obj5.Rank = 1;

obj6.Name = "PQR";
obj6.Rank = 4;

I need to sort these objects in following order.

obj5,
obj3,
obj2,
obj6,
obj1,
obj4.

I have tried following code,

Collections.sort(studentList, new Comparator<Student>() {
    @Override
    public int compare(Student obj2, Student obj1) {
            return obj2.Rank.compareTo(obj1.Rank);
    }
});

I am getting following result.

obj4,//this should be in last position
obj5,
obj3,
obj2,
obj6,
obj1.

But I need all zero’s should be at last.

Advertisement

Answer

A better way to sort them with 0 higher than any value is:

Collections.sort(StudentList, new Comparator<Student>() {
    @Override
    public int compare(Student obj1, Student obj2) {
        if(obj1.Rank==0) return (obj2.Rank==0) ? 0 : 1;
        if(obj2.Rank==0) return -1;
        return Integer.compare(obj1.Rank,obj2.Rank);
    }
});

This will correctly handle the case where obj.Rank=Integer.MAX_VALUE.

If your Ranks are Integers rather than ints you’ll also need to handle the case where they’re null.

Advertisement