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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41141672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:42:22  来源:igfitidea点击:

java - Sorting in Descending order using comparator

javasorting

提问by Aishu

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?

谁能告诉我为什么降序排序不起作用?

回答by Eran

Your two ternary conditional operators produce the same result (since you swapped both >with <and -1with 1):

您的两个三元条件运算符产生相同的结果(因为您交换了>with<-1with 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);

回答by lexicore

@Eran already pointed out the error in your comparator.

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

I'd like to add that you may just return o1.age - o2.age. The result of comparison does not have to be exactly -1or 1for <or >it may be just negative or positive.

我想补充一点,您可以直接返回o1.age - o2.age。比较的结果不一定是精确的-1或完全的1<或者>它可能只是负面的或正面的。

And you could have also called Comparator.reversed. Or Comparator.comparing(Student::getAge).reversed().

你也可以调用Comparator.reversed. 或者Comparator.comparing(Student::getAge).reversed()

回答by davidxxx

Abusing ternary conditions is error-prone because not readable.

滥用三元条件容易出错,因为不可读。

Why not simply write classic if-else-iffor the descending comparator ?

为什么不简单地if-else-if为降序比较器编写经典?

public class AgeComparatorDesc implements Comparator<Student> {

  @Override
  public int compare(Student o1, Student o2) {
    if (o1.age > o2.age) {
        return -1;
    } else if (o1.age < o2.age) {
        return 1;
    }    
     return 0;
  }

}

回答by Akhil Ghatiki

You can directly use a comparator class instance. Below is the code example.

您可以直接使用比较器类实例。下面是代码示例。

Assuming the you define a getter method "getAge()"for student.

假设您"getAge()"为学生定义了一个 getter 方法。

Comparator<Student> m_studentComparator = new Comparator<Sudent>() {
        @Override
        public int compare(Student lhs, Student rhs) {
            return rhs.getAge().compareTo(lhs.getAge());  // Descending order
        }
    };

Collections.sort(<<Your list>> , m_studentComparator);   // this would return the descending order list.

If you want an Ascending order list, just change the return statement in the overridden method to

如果你想要一个升序列表,只需将覆盖方法中的返回语句更改为

return lhs.getAge().compareTo(rjs.getAge());    // Ascending order.

Hope this answers your question.

希望这能回答你的问题。

回答by Stanley Kou

The age value is an integer, and it seems that it is always positive, you can use this shorten code.

年龄值是一个整数,看起来总是正数,可以使用这个缩短代码。

return o1.age - o2.age; // Ascending
return o2.age - o1.age; // Descending

This code cannot be used for negative values.

此代码不能用于负值。

For example,

例如,

if o1.age = 10, o2.age = 11, this code will return -1for ascending and 1for descending, that is correct.

如果o1.age = 10, o2.age = 11,则此代码将返回-1升序和1降序,这是正确的。

But the case o1.age = -10, o2.age = -11, this code will return 1for ascending and -1for descending, that is incorrect.

但这种情况下o1.age = -10o2.age = -11此代码将返回1升序和-1降序,这是不正确的。

回答by skY

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

though for descending simply just multiply your ascending return statement with -1. like this

虽然对于降序,只需将升序返回语句乘以 -1。像这样

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

回答by user3437460

Well you should either write it as:

那么你应该把它写成:

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

or write it as:

或写成:

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

Your current attempt will still sort it in ascending order.

您当前的尝试仍将按升序对其进行排序。