java lambda分组后再排序
时间: 2023-09-01 12:11:12 浏览: 143
java 集合分组与排序
4星 · 用户满意度95%
可以使用Java 8中的Stream API和lambda表达式来实现分组后排序的功能。下面是一个示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class GroupingAndSortingExample {
public static void main(String[] args) {
// 创建一个学生列表
List<Student> students = Arrays.asList(
new Student("Tom", 18, 80),
new Student("Jerry", 17, 90),
new Student("Lucy", 18, 95),
new Student("Bob", 17, 85),
new Student("Alice", 18, 92)
);
// 按年龄分组,并按分数排序
Map<Integer, List<Student>> map = students.stream()
.collect(Collectors.groupingBy(Student::getAge,
Collectors.collectingAndThen(Collectors.toList(),
list -> list.stream()
.sorted(Comparator.comparing(Student::getScore))
.collect(Collectors.toList()))));
// 打印结果
map.forEach((age, list) -> {
System.out.println("Age: " + age);
list.forEach(System.out::println);
});
}
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
```
以上代码将学生列表按年龄分组,并按照分数进行排序。可以根据需要修改Student类的字段和排序方式。
阅读全文