stream流分组归类
时间: 2023-09-22 18:10:45 浏览: 112
Stream流的思维导图
使用Stream流对数据进行分组归类可以通过Stream的collect方法结合Collectors.groupingBy方法来实现。groupingBy方法接受一个Function作为参数,用于指定根据哪个属性进行分组。下面是一个示例代码:
```java
List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
Map<Integer, List<String>> groupedMap = list.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(groupedMap);
```
以上代码将根据字符串的长度进行分组,输出的结果为:
```java
{5=[apple], 6=[banana, cherry], 4=[date], 9=[elderberry]}
```
其中,键是字符串的长度,值是对应长度的字符串列表。可以看到,长度为5的字符串有一个,长度为6的字符串有两个,长度为4和9的字符串各有一个。
这样就实现了对Stream流中的元素进行分组归类。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Java8 Stream-深入理解筛选、归约、分组、聚合](https://blog.csdn.net/oschina_41731918/article/details/121627314)[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: 50%"]
- *2* [Java8种Stream流相关操作——集合的筛选、归约、分组、聚合](https://blog.csdn.net/shooter7/article/details/123354121)[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: 50%"]
[ .reference_list ]
阅读全文