
java streams中的reduce()和collect()方法服务于不同的目的并在不同的抽象级别上运行。详细对比如下:
1。减少()
reduce() 方法用于使用归约操作(例如求和、连接、求最小值/最大值)将元素流缩减为单个结果。
主要特征:
立即学习“Java免费学习笔记(深入)”;
适用于不可变的归约。
对流进行操作以产生单个结果(例如,整数、双精度、字符串)。
通常与关联、互不干扰和无状态操作一起使用。
reduce() 用法示例:
求和:
list numbers = list.of(1, 2, 3, 4, 5);int sum = numbers.stream() .reduce(0, integer::sum); // 0 is the identity valuesystem.out.println(sum); // output: 15
连接字符串:
list words = list.of("hello", "world");string result = words.stream() .reduce("", (s1, s2) -> s1 + " " + s2);system.out.println(result.trim()); // output: hello world
找到最大值:
list numbers = 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 类结合使用。
有道小P
有道小P,新一代AI全科学习助手,在学习中遇到任何问题都可以问我。
64 查看详情
collect() 用法示例:
收集到列表中:
list numbers = list.of(1, 2, 3, 4, 5);list result = numbers.stream() .collect(collectors.tolist());system.out.println(result); // output: [1, 2, 3, 4, 5]
收集成一个集合:
list numbers = list.of(1, 2, 2, 3, 4, 4);set result = numbers.stream() .collect(collectors.toset());system.out.println(result); // output: [1, 2, 3, 4]
对元素进行分组:
list names = list.of("alice", "bob", "anna", "charlie");map<character, list> 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():
list numbers = 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()(对于此任务不太理想,但可能):
List numbers = 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()。
以上就是Java 流中的reduce() 与collect() 有何不同?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/379650.html
微信扫一扫
支付宝扫一扫