当前位置: 代码网 > it编程>编程语言>Java > Java Stream Collectors功能实现方法全面指南

Java Stream Collectors功能实现方法全面指南

2026年08月09日 Java 我要评论
collectors 是 java stream api 中最强大的工具之一,提供了丰富的收集器实现,用于将流中的元素聚合为各种结果。常用收集器1.tolist()- 收集为列表list<str

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)
);
// 获取: count, sum, min, max, average

用途:获取数值流的统计摘要信息

分组与分区

7.groupingby()- 分组

// 基础分组
map<string, list<employee>> grouped = stream.collect(
    collectors.groupingby(employee::getdepartment)
);

// 带下游收集器分组
map<string, set<string>> grouped = stream.collect(
    collectors.groupingby(
        employee::getdepartment,
        collectors.mapping(employee::getname, collectors.toset())
    )
);

用途:按分类函数对元素分组

8.partitioningby()- 分区

map<boolean, list<integer>> partitioned = stream.collect(
    collectors.partitioningby(n -> n % 2 == 0)
);
// 结果: {false=[奇数], true=[偶数]}

用途:按谓词将元素分为两组(true/false)

归约操作

9.reducing()- 归约

// 基础归约
optional<integer> sum = stream.collect(
    collectors.reducing(integer::sum)
);

// 带初始值归约
integer sum = stream.collect(
    collectors.reducing(0, integer::sum)
);

// 带映射和归约
optional<integer> sum = stream.collect(
    collectors.reducing(
        employee::getsalary,
        integer::sum
    )
);

用途:通过二元运算将元素归约为单个值

10.summingint/long/double()- 求和

integer sum = stream.collect(collectors.summingint(integer::intvalue));

用途:对数值流求和

11.averagingint/long/double()- 求平均值

double average = stream.collect(collectors.averagingint(integer::intvalue));

用途:计算数值流的平均值

极值获取

12.maxby()/minby()- 最大/最小值

optional<integer> max = stream.collect(collectors.maxby(integer::compareto));
optional<integer> min = stream.collect(collectors.minby(integer::compareto));

用途:获取流中的最大/最小元素

13.collectingandthen()- 转换结果

list<string> unmodifiablelist = stream.collect(
    collectors.collectingandthen(
        collectors.tolist(),
        collections::unmodifiablelist
    )
);

用途:收集后对结果进行转换

高级收集器

14.mapping()- 映射收集

set<string> names = stream.collect(
    collectors.mapping(
        employee::getname,
        collectors.toset()
    )
);

用途:先映射再收集

15.flatmapping()- 扁平映射收集(java 9+)

set<string> allskills = stream.collect(
    collectors.flatmapping(
        emp -> emp.getskills().stream(),
        collectors.toset()
    )
);

用途:扁平化映射后收集

16.filtering()- 过滤收集(java 9+)

list<employee> senior = stream.collect(
    collectors.filtering(
        emp -> emp.getage() > 50,
        collectors.tolist()
    )
);

用途:过滤后再收集

自定义收集器

17.of()- 创建自定义收集器

collector<string, ?, string> customcollector = collector.of(
    stringbuilder::new,           // supplier: 创建可变容器
    stringbuilder::append,        // accumulator: 累加元素
    stringbuilder::append,        // combiner: 合并容器
    stringbuilder::tostring       // finisher: 转换结果
);

用途:创建完全自定义的收集器

收集器组合

18. 多重收集器

// 同时进行多种收集
map<string, object> result = stream.collect(
    collectors.teeing(
        collectors.counting(),
        collectors.summingdouble(double::doublevalue),
        (count, sum) -> map.of("count", count, "sum", sum)
    )
);

用途:在一个操作中执行多个收集器(java 12+)

实用示例

示例 1:员工数据处理

// 按部门分组,收集员工姓名
map<string, list<string>> departmentemployees = employees.stream()
    .collect(collectors.groupingby(
        employee::getdepartment,
        collectors.mapping(employee::getname, collectors.tolist())
    ));

// 按部门统计薪资
map<string, double> departmentsalary = employees.stream()
    .collect(collectors.groupingby(
        employee::getdepartment,
        collectors.summingdouble(employee::getsalary)
    ));

示例 2:数据转换

// 将列表转换为不可变 map
map<integer, employee> employeemap = employees.stream()
    .collect(collectors.tounmodifiablemap(
        employee::getid,
        function.identity()
    ));

// 字符串拼接
string employeenames = employees.stream()
    .map(employee::getname)
    .collect(collectors.joining(", "));

注意事项

问题解决方案
tolist() 返回可变列表使用 tounmodifiablelist() 获取不可变列表
tomap() key 冲突提供合并函数作为第三个参数
并发修改异常使用线程安全的收集器或并行流时注意
空元素处理在收集前过滤或处理空值

版本兼容性

收集器最低版本
基础收集器java 8
flatmapping, filteringjava 9
teeingjava 12
tounmodifiablelist/set/mapjava 10

总结

collectors 提供了强大的数据收集能力:

  • 基础收集tolist, toset, tomap, joining
  • 聚合操作counting, summing, averaging, reducing
  • 分组分区groupingby, partitioningby
  • 高级功能collectingandthen, teeing, 自定义收集器

到此这篇关于java stream collectors功能实现方法全面指南的文章就介绍到这了,更多相关java stream collectors功能内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com