
java streams中的reduce()和collect()方法服务于不同的目的并在不同的抽象级别上运行。详细对比如下:
1。减少()
reduce() 方法用于使用归约操作(例如求和、连接、求最小值/最大值)将元素流缩减为单个结果。
主要特征:
立即学习“Java免费学习笔记(深入)”;
适用于不可变的归约。
对流进行操作以产生单个结果(例如,整数、双精度、字符串)。
通常与关联、互不干扰和无状态操作一起使用。
reduce() 用法示例:
求和:
listnumbers = list.of(1, 2, 3, 4, 5); int sum = numbers.stream() .reduce(0, integer::sum); // 0 is the identity value system.out.println(sum); // output: 15
连接字符串:
listwords = list.of("hello", "world"); string result = words.stream() .reduce("", (s1, s2) -> s1 + " " + s2); system.out.println(result.trim()); // output: hello world
找到最大值:
listnumbers = list.of(1, 2, 3, 4, 5); int max = numbers.stream() .reduce(integer.min_value, integer::max); system.out.println(max); // output: 5
reduce() 的局限性:
产生单个值。
与collect()相比灵活性较差,尤其是对于可变减少。
2。收集()
collect() 方法用于将元素累积到可变容器(例如 list、set、map)中或执行更复杂的缩减。它通常与收集器实用方法一起使用。
主要特征:
立即学习“Java免费学习笔记(深入)”;
专为可变缩减而设计。
生成集合或其他复杂结果,例如 list、set、map 或自定义结构。
与 collectors 类结合使用。
拥有企业网站常用的模块功能:企业简介模块、联系我们模块、新闻(文章)模块、产品模块、图片模块、招聘模块、在线留言、反馈系统、在线交流、友情链接、网站地图、栏目管理、网站碎片、管理员与权限管理等等,所有模块的分类均支持无限级别的分类,可拓展性非常强大。其中包括万能的栏目管理系统、网站碎片管理系统,通过这些系统,可以组合出各种不同的页面和应用。系统带强大灵活的后台管理功能、支持伪静态URL页面功能、自
collect() 用法示例:
收集到列表中:
listnumbers = list.of(1, 2, 3, 4, 5); list result = numbers.stream() .collect(collectors.tolist()); system.out.println(result); // output: [1, 2, 3, 4, 5]
收集成一个集合:
listnumbers = list.of(1, 2, 2, 3, 4, 4); set result = numbers.stream() .collect(collectors.toset()); system.out.println(result); // output: [1, 2, 3, 4]
对元素进行分组:
listnames = list.of("alice", "bob", "anna", "charlie"); map > groupedbyfirstletter = names.stream() .collect(collectors.groupingby(name -> name.charat(0))); system.out.println(groupedbyfirstletter); // output: {a=[alice, anna], b=[bob], c=[charlie]}
collect()相对于reduce()的优点:
与集合等可变容器一起使用。
通过有效组合部分结果来支持并行处理。
通过 collectors 提供各种预建的收集器。
何时使用哪个?
使用reduce() 时:
您需要来自流的单个结果(例如,总和、乘积、最大值、最小值)。
归约逻辑简单且具有关联性。
使用collect() 时:
您需要将流转换为集合(例如list、set、map)。
您需要进行分组、分区或执行复杂的累加。
您想要使用预构建的收集器来执行常见任务。
示例比较
任务:对列表中数字的平方求和。
使用reduce():
listnumbers = list.of(1, 2, 3, 4); int sumofsquares = numbers.stream() .map(n -> n * n) .reduce(0, integer::sum); system.out.println(sumofsquares); // output: 30
使用collect()(对于此任务不太理想,但可能):
Listnumbers = List.of(1, 2, 3, 4); int sumOfSquares = numbers.stream() .map(n -> n * n) .collect(Collectors.summingInt(Integer::intValue)); System.out.println(sumOfSquares); // Output: 30
一般来说,对于简单、不可变的缩减,更喜欢使用 reduce() ,对于涉及集合或更复杂操作的任何内容,更喜欢使用collect()。









