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 方法不一致?
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01