stream groupby 排序
时间: 2023-08-22 19:08:13 浏览: 89
java1.8 中 stream 的 groupingBy 最大值、最小值分组
如果你想在对流对象进行`group by`操作后对每个组进行排序,可以在`groupingBy`方法的第二个参数中指定`Collectors.toList()`来收集元素,并在`toCollection`方法中传入一个自定义的排序比较器。以下是一个示例代码:
```java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> persons = List.of(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 20),
new Person("Dave", 25),
new Person("Eve", 30)
);
Map<Integer, List<Person>> groupedByAgeSorted = persons.stream()
.collect(Collectors.groupingBy(
Person::getAge,
Collectors.toList()
));
groupedByAgeSorted.forEach((age, group) -> {
System.out.println("Age: " + age);
System.out.println("Group: " + group);
List<Person> sortedGroup = group.stream()
.sorted(Comparator.comparing(Person::getName))
.collect(Collectors.toList());
System.out.println("Sorted Group: " + sortedGroup);
});
}
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
阅读全文