简体   繁体   English

如何按字段按降序对列表进行排序?

[英]How to sort List by field in descending order?

I am trying to achieve a sort for object's field value stored in List.我正在尝试对存储在 List 中的对象字段值进行排序。

I found the following solution to compare the string but How I can compare the String value and sort accordingly?我找到了以下解决方案来比较字符串,但是如何比较字符串值并进行相应排序?

I am looking to sort the "Y" status values first then "N"我希望先对“Y”状态值进行排序,然后再对“N”进行排序

class Student {
    int rollno;
    String name, status;

    // Constructor
    public Student(int rollno, String name,
        String status) {
        this.rollno = rollno;
        this.name = name;
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

}
ArrayList < Student > ar = new ArrayList < Student > ();
ar.add(new Student(111, "bbbb", "Y"));
ar.add(new Student(131, "aaaa", "N"));
ar.add(new Student(121, "cccc", "Y"));

Collections.sort(ar, (a, b) - > a.getStatus().compareTo(b.getStatus()));

If I understood correctly you need refence to method getStatus() its natural order sort如果我理解正确,您需要参考方法 getStatus() 它的自然顺序排序

ar.sort(Comparator.comparing(Student::getStatus));

if need reverse order如果需要倒序

ar.sort(Comparator.comparing(Student::getStatus).reversed());

The string "Y" comes lexicographically after "N", so you need to reverse the default ordering.字符串“Y”按字典顺序出现在“N”之后,因此您需要颠倒默认顺序。

There are some ways to do it, one is negating the result of the comparison function:有一些方法可以做到,一种是否定比较function的结果:

Collections.sort(ar, (a, b) - > -a.getStatus().compareTo(b.getStatus());

Another is changing the order of the operands:另一个是改变操作数的顺序:

Collections.sort(ar, (a, b) - > b.getStatus().compareTo(a.getStatus());

For this, you need a comparator class, that will compare the two students, in that case, if you want that when a student have "Y" in status, it's sorted before "N", you will need something like that:为此,您需要一个比较器 class,它将比较两个学生,在这种情况下,如果您希望当学生的状态为“Y”时,它排在“N”之前,您将需要这样的东西:

    public static class StudentComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        // Compare the students, return -1 if o1 is "greater" than o2. Return 1 if o2 is "greater" than o1
        if (o1.status.equals("Y")) return -1;
        if (o2.status.equals("Y")) return 1;
        return 0;
    }
}

And then you can compare like that:然后你可以这样比较:

    List<Student> ar = new ArrayList<Student>();
    ar.add(new Student(111, "bbbb", "Y"));
    ar.add(new Student(131, "aaaa", "N"));
    ar.add(new Student(121, "cccc", "Y"));

    Collections.sort(ar, new StudentComparator());

Output: Output:

[Student{rollno=121, name='cccc', status='Y'}, Student{rollno=111, name='bbbb', status='Y'}, Student{rollno=131, name='aaaa', status='N'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM