使用java的shteam流对一个list进行排序,先按照成绩排序,成绩一样时按照年龄排序,举个例子
时间: 2023-06-05 10:07:15 浏览: 47
我可以回答您的问题。您可以使用Java中的Collections.sort方法,并编写一个比较器来实现该需求。以下是一个例子:
```
import java.util.*;
public class Student {
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getScore() {
return score;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 25, 90));
students.add(new Student("Ben", 23, 85));
students.add(new Student("Charlie", 25, 85));
// Sort by score, then age
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.getScore() != s2.getScore()) {
// Sort by score in descending order
return s2.getScore() - s1.getScore();
} else {
// Sort by age in ascending order
return s1.getAge() - s2.getAge();
}
}
});
for (Student student : students) {
System.out.println(student.getName() + " - Age: " + student.getAge() + ", Score: " + student.getScore());
}
}
}
```
输出结果为:
```
Alice - Age: 25, Score: 90
Charlie - Age: 25, Score: 85
Ben - Age: 23, Score: 85
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)