stream.groupingBy
时间: 2023-10-21 17:05:52 浏览: 97
stream.groupingBy是Java 8中的一个方法,用于将流按照指定的条件进行分组。这个方法接受一个Function参数,用于指定分组的条件。根据这个条件,流中的元素会被分成不同的组,并以分组的方式返回一个Map对象。Map的键是分组的条件,值是符合条件的元素列表。如果分组条件是多个字段,可以使用Collectors.groupingBy和Function来处理。具体的用法可以参考以下代码示例:
```java
import java.util.stream.Collectors;
import java.util.List;
import java.util.Map;
public class Employee {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
public class Main {
public static void main(String[] args) {
List<Employee> employees = // 假设有一个Employee列表
// 按城市分组
Map<String, List<Employee>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getCity));
// 打印分组结果
map.forEach((k, v) -> {
System.out.println(k + " = " + v);
});
}
}
```
以上代码中,通过stream.groupingBy方法按照Employee对象的城市字段进行分组,返回一个Map,键是城市名,值是对应城市的Employee对象列表。然后通过forEach遍历Map,打印出每个城市对应的员工列表。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [java1.8 中 stream 的 groupingBy 最大值、最小值分组](https://download.csdn.net/download/qq_42711127/18909862)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Java stream多字段分组(groupingBy)](https://blog.csdn.net/m0_58016522/article/details/131082125)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [Java笔记--Stream之groupingBy 分组讲解](https://blog.csdn.net/Schaffer_W/article/details/119787802)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文