stream流 groupby后排序
时间: 2023-08-22 22:08:51 浏览: 116
对于流(Stream)对象,你可以使用`groupingBy`方法对其进行分组,然后使用`sorted`方法对每个组进行排序。下面是一个示例代码:
```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>> groupedByAge = persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
groupedByAge.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
阅读全文