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

本文探讨了使用Java Comparator接口对Student对象列表按年龄降序排序的问题。代码示例中,升序排序正确实现,但降序排序未生效。错误在于比较方法的条件判断未正确翻转。修正后的代码应为`return o1.age > o2.age ? -1 : (o1.age < o2.age ? 1 : 0);`以实现降序排序。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值