Why is the combiner of the Collector interface not consistent with the overloaded collect method?(为什么 Collector 接口的 combiner 与重载的 collect 方法不一致?)
问题描述
接口Stream<T>
中有一个重载方法collect()
,签名如下:
There is an overload method, collect()
, in interface Stream<T>
with the following signature:
<R> R collect(Supplier<R> supplier,
BiConsumer<R,? super T> accumulator,
BiConsumer<R,R> combiner)
还有另一个版本的collect(Collectorcollector)
,它接收一个具有前面三个函数的对象.combiner
对应的接口Collector
的属性有签名BinaryOperator;组合器()
.
There is another version of collect(Collector<? super T,A,R> collector)
, which receives an object with the previous three functions. The property of the interface Collector
corresponding to the combiner
has the signature BinaryOperator<A> combiner()
.
在后一种情况下,Java API 8 声明:
In the latter case, the Java API 8 states that:
组合器函数可以将状态从一个参数折叠到另一个参数并返回,或者可以返回一个新的结果容器.
The combiner function may fold state from one argument into the other and return that, or may return a new result container.
为什么以前的 collect
方法也没有收到 BinaryOperator
?
Why does the former collect
method not receive a BinaryOperator<R>
too?
推荐答案
collect
的内联"(3-arg)版本是专为当您已经拥有这些功能闲置"的时候而设计的.例如:
The "inline" (3-arg) version of collect
is designed for when you already have these functions "lying around". For example:
ArrayList<Foo> list = stream.collect(ArrayList::new,
ArrayList::add,
ArrayList::addAll);
或者
BitSet bitset = stream.collect(BitSet::new,
BitSet::set,
BitSet::or);
虽然这些只是激励性示例,但我们对现有类似构建器类的探索是,现有组合器候选者的签名更适合转换为 BiConsumer,而不是 BinaryOperator.提供您所要求的灵活性"将使这种重载在它旨在支持的情况下变得不那么有用 - 这是当您已经拥有这些功能并且您不想让 (或学习制作)收集器只是为了收集它们.
While these are just motivating examples, our explorations with similar existing builder classes was that the signatures of the existing combiner candidates were more suited to conversion to BiConsumer than to BinaryOperator. Offering the "flexibility" you ask for would make this overload far less useful in the very cases it was designed to support -- which is when you've already got the functions lying around, and you don't want to have to make (or learn about making) a Collector just to collect them.
另一方面,收集器具有更广泛的用途,因此具有额外的灵活性.
Collector, on the other hand, has a far wider range of uses, and so merits the additional flexibility.
这篇关于为什么 Collector 接口的 combiner 与重载的 collect 方法不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Collector 接口的 combiner 与重载的 collect 方法不一致?
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01