Reputation: 15515
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.
Upvotes: 1
Views: 90
Reputation: 73480
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 Rank
s are Integers rather than int
s you'll also need to handle the case where they're null
.
Upvotes: 2
Reputation: 81
You can edit compare method , and put a check for zero
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student obj2, Student obj1) {
if(obj1.rank ==0 ){
if(obj2.rank ==0){
// when both count are zero then you can handle here
}
// return positive int beacuse zero is greater than everyother count
}
else return obj2.Rank.compareTo(obj1.Rank);
}
});
Upvotes: 0
Reputation: 16215
If you want to put 0's last in sort order, and leave others in ascending order (ie: 1, 2, 3, 4, 5, 0), you'll need to write a custom Comparator
that treats 0's as the largest value. Possibly something like this:
Collections.sort(StudentList, new Comparator<Student>() {
@Override
public int compare(Student obj1, Student obj2) {
Integer compareRank1 = obj1.Rank == 0 ? Integer.MAX_VALUE : obj1.Rank;
Integer compareRank2 = obj2.Rank == 0 ? Integer.MAX_VALUE : obj2.Rank;
return compareRank1.compareTo(compareRank2);
}
});
Upvotes: 1