为什么 Collector 接口的 combiner 与重载的 collect 方法不一致? [英] Why is the combiner of the Collector interface not consistent with the overloaded collect method?

查看:51
本文介绍了为什么 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 方法不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆