java8 groupby
时间: 2023-12-27 20:24:07 浏览: 72
JAVA8 STREAM COLLECT GROUPBY分组实例解析
以下是两种使用Java 8的groupingBy操作进行分组的例子:
1.基于city和name实现多次分组:
```java
Map<String, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getCity, Collectors.groupingBy(Employee::getName)));
map.forEach((k, v) -> {
System.out.println(k + " = " + v);
v.forEach((i, j) -> {
System.out.println(i + " = " + j);
});
});
```
2.按城市分组list:
```java
Map<String, List<Employee>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getCity));
map.forEach((k, v) -> {
System.out.println(k + " = " + v);
});
```
阅读全文