
java streams中的reduce()和collect()方法服务于不同的目的并在不同的抽象级别上运行。详细对比如下:
1。减少()
reduce() 方法用于使用归约操作(例如求和、连接、求最小值/最大值)将元素流缩减为单个结果。
主要特征:
立即学习“Java免费学习笔记(深入)”;
适用于不可变的归约。
对流进行操作以产生单个结果(例如,整数、双精度、字符串)。
通常与关联、互不干扰和无状态操作一起使用。
reduce() 用法示例:
求和:
list<integer> numbers = 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
连接字符串:
list<string> words = list.of("hello", "world");
string result = words.stream()
.reduce("", (s1, s2) -> s1 + " " + s2);
system.out.println(result.trim()); // output: hello world
找到最大值:
list<integer> 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 类结合使用。
collect() 用法示例:
收集到列表中:
list<integer> numbers = list.of(1, 2, 3, 4, 5);
list<integer> result = numbers.stream()
.collect(collectors.tolist());
system.out.println(result); // output: [1, 2, 3, 4, 5]
收集成一个集合:
list<integer> numbers = list.of(1, 2, 2, 3, 4, 4);
set<integer> result = numbers.stream()
.collect(collectors.toset());
system.out.println(result); // output: [1, 2, 3, 4]
对元素进行分组:
list<string> names = list.of("alice", "bob", "anna", "charlie");
map<character, list<string>> 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<integer> 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<Integer> 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() 有何不同?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号