java-使用比较器以降序排序 [英] java - Sorting in Descending order using comparator

查看:259
本文介绍了java-使用比较器以降序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用比较器界面按降序对列表进行排序.但是这些值不是按降序排列的.不知道我在这里做错了什么.

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<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);
        }

    }

}

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

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?

推荐答案

您的两个三元条件运算符会产生相同的结果(因为您同时将><以及-11交换了):

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

对于降序,您需要:

return o1.age > o2.age ? -1 :(o1.age < o2.age ? 1 : 0);

这篇关于java-使用比较器以降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆