Java Stream Collectors 功能全面指南
Collectors 是 Java Stream API 中最强大的工具之一,提供了丰富的收集器实现,用于将流中的元素聚合为各种结果。
常用收集器
1. toList() - 收集为列表
List<String> list = stream.collect(Collectors.toList());
用途:将流元素收集到 List 中
返回:ArrayList(非线程安全)
2. toSet() - 收集为集合
Set<Integer> set = stream.collect(Collectors.toSet());
用途:将流元素收集到 Set 中(自动去重)
返回:HashSet
3. toMap() - 收集为映射
Map<String, Integer> map = stream.collect(
Collectors.toMap(
Function.identity(), // key 映射
Function.identity() // value 映射
)
);
用途:将流元素收集到 Map 中
注意:需要处理 key 冲突,可通过第三个参数指定合并策略
4. joining() - 字符串连接
String result = stream.collect(Collectors.joining());
// 带分隔符
String result = stream.collect(Collectors.joining(", "));
// 带分隔符、前缀、后缀
String result = stream.collect(Collectors.joining(", ", "[", "]"));
用途:将字符串流连接成单个字符串
5. counting() - 计数
Long count = stream.collect(Collectors.counting());
用途:统计流中元素数量
也可用:stream.count()(更简洁)
6. summarizingInt/Long/Double() - 统计摘要
IntSummaryStatistics stats = stream.collect(
Collectors.summarizingInt(Integer::intValue


2604

被折叠的 条评论
为什么被折叠?



