java - 使用比较器以降序排序

Ais*_*shu 7 java sorting

我正在尝试使用Comparator接口按降序对列表进行排序.但是值不按降序排序.不知道我在这里做错了什么.

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<Student>{

    @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<Student> al = new ArrayList<Student>();
        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);
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

我可以按升序对列表进行排序,而我无法按降序排序

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
Run Code Online (Sandbox Code Playgroud)

比较器文档 - 返回:负整数,零或正整数,因为第一个参数小于,等于或大于第二个参数.来源是从这里找到的

任何人都可以告诉我为什么下降的排序不起作用?

Era*_*ran 9

你的两个三元条件运算符产生相同的结果(因为你俩交换><-11):

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
Run Code Online (Sandbox Code Playgroud)

对于降序,您需要:

return o1.age > o2.age ? -1 :(o1.age < o2.age ? 1 : 0);
Run Code Online (Sandbox Code Playgroud)


lex*_*ore 5

@Eran已经指出比较器中的错误.

我想补充一点,你可能会回来o1.age - o2.age.比较的结果不一定是完全-11<或者>可能只是消极或积极的.

而你也可以打电话Comparator.reversed.或者Comparator.comparing(Student::getAge).reversed().