gpt4 book ai didi

java - 使用java在同一程序中的升序和降序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:51 28 4
gpt4 key购买 nike

我想根据 id 和标记对对数据进行排序。ID 应按升序排列,标记应按降序排列,这是我的代码:

ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(1,"dg",58));
al.add(new Student(2,"dg",48));
al.add(new Student(1,"dg",98));
al.add(new Student(2,"dg",68));
al.add(new Student(1,"dg",38));
al.add(new Student(2,"dg",28));
al.add(new Student(2,"dg",90));

输出如下:

1 dg 98  
1 dg 58
1 dg 38
2 dg 90
2 dg 68
2 dg 48
2 dg 28

最佳答案

您必须实现 Comparable对于 Student 类或直接使用自定义 Comparator 对其进行排序:

Comparator<Student> comparator = Comparator
.comparing(Student::getId) // First ID in ascending order
.thenComparing(Comparator.comparing(Student::getMark) // Then mark
.reversed()); // ... but in descending order

al.sort(comparator); // Here is the sort performed

关于java - 使用java在同一程序中的升序和降序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53629791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com