【问题标题】:How to sort List by field in descending order? [duplicate]如何按字段按降序对列表进行排序? [复制]
【发布时间】:2022-01-04 17:24:19
【问题描述】:

我正在尝试对存储在 List 中的对象的字段值进行排序。

我找到了以下比较字符串的解决方案,但是我如何比较字符串值并进行相应的排序?

我希望先对“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()));

【问题讨论】:

  • edit 发帖并修正语法错误。 --- 我建议为status 使用适当的对象或枚举,而不是String
  • 您的问题缺少一些信息。当字符串既不是“Y”也不是“N”时,预期的行为是什么?我将status 转换为枚举并实现该枚举的比较会更简单。
  • 你好。我试图澄清一下这个问题的标题。如果您不同意我的编辑,请随时 rolback 它(edit revision 中有一个选项 - 在我编辑之前选择版本并使用其 rolback 选项)。

标签: java sorting collections


【解决方案1】:

如果我理解正确,您需要参考 getStatus() 方法 它的自然顺序排序

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

如果需要倒序

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

【讨论】:

    【解决方案2】:

    字符串“Y”按字典顺序排在“N”之后,因此您需要颠倒默认顺序。

    有一些方法可以做到,一种是否定比较函数的结果:

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

    另一个是改变操作数的顺序:

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

    【讨论】:

    • 这些很聪明,但我认为它们缺乏可读性。我的意思是看代码倒序效果不是很明显。
    • 这很聪明,因为大多数人不会考虑这种特殊的方法来解决这个问题。如果我们“google”这个问题,有多少百分比的结果会显示这个答案?这就是为什么我说它很聪明。
    【解决方案3】:

    为此,您需要一个比较器类,它将比较两个学生,在这种情况下,如果您希望当学生的状态为“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;
        }
    }
    

    然后你可以这样比较:

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

    输出:

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

    【讨论】:

    • 您的Comparator#compare(Student, Student) 方法可以简单地返回比较两个“状态”字符串的结果:return o1.getStatus().compareTo(o2.getStatus());。您无需执行所有这些逻辑,因为 String 本质上具有可比性。
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多