I'm trying to sort the list in descending order using Comparator Interface. But the values are not sorted in descending order. Not sure what i'm doing wrong here.
public class Student {
int rollNo;
String name;
int age;
public Student(int RollNo, String Name, int Age){
this.rollNo = RollNo;
this.name = Name;
this.age = Age;
}
}
public class AgeComparator implements Comparator{
@Override
public int compare(Student o1, Student o2) {
return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Ascending
//return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Descending
}
}
public class Comparator_Sort {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList al = new ArrayList();
al.add(new Student(5978,"Vishnu", 50));
al.add(new Student(5979,"Vasanth", 30));
al.add(new Student(5980,"Santhosh", 40));
al.add(new Student(5981,"Santhosh", 20));
al.add(new Student(5982,"Santhosh", 10));
al.add(new Student(5983,"Santhosh", 5));
Collections.sort(al, new AgeComparator());
for(Student s : al){
System.out.println(s.rollNo+" "+s.name+" "+s.age);
}
}
}
I can be able to sort the list in ascending order, whereas i'm unable to do it for descending order
return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Sorted in Ascending
return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Not sorted in Descending
Comparator documentation -- Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. The source is found from here
Can anyone tell me why the sorting for descending is not working?
解决方案
Your two ternary conditional operators produce the same result (since you swapped both > with < and -1 with 1):
return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Sorted in Ascending
return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Not sorted in Descending
For descending order you need :
return o1.age > o2.age ? -1 :(o1.age < o2.age ? 1 : 0);