什么Collector接口的组合器与重载的collect方法不一

什么Collector接口的组合器与重载的collect方法不一

本文介绍了为什么Collector接口的组合器与重载的collect方法不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在接口 Stream< T> 中有一个重载方法 collect(),带有以下签名:

 < R> R collect(供应商< R>供应商,
BiConsumer< R,?super T>累加器,
BiConsumer< R,R>组合器)

还有另一个版本的 collect(Collector<?super T,A,R> collector),它接收一个具有前三个功能的对象。对应于组合器的接口 Collector 的属性具有签名 BinaryOperator< A> combiner()



在后一种情况下,Java API 8声明:

为什么前 collect 方法也没有收到 BinaryOperator< R>

解决方案

设计了 collect 的内联(3-arg)版本因为当你已经拥有这些躺着的功能时。例如:

  ArrayList< Foo> list = stream.collect(ArrayList :: new,
ArrayList :: add,
ArrayList :: addAll);

  BitSet bitset = stream.collect(BitSet :: new,
BitSet :: set,
BitSet :: or);

虽然这些仅仅是激励性的例子,但我们对类似的现有构建器类的探索是现有的签名合并器候选者更适合转换为BiConsumer而不是BinaryOperator。提供你所要求的灵活性会使这种过载在它被设计为支持的情况下变得不那么有用 - 也就是说,当你已经有了功能,并且你不想做(或者学习制作)收藏家只是为了收集它们。



另一方面,收藏家具有更广泛的用途,因此具有额外的灵活性。 / p>

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)

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().

In the latter case, the Java API 8 states that:

Why does the former collect method not receive a BinaryOperator<R> too?

解决方案

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);

Or

BitSet bitset = stream.collect(BitSet::new,
                               BitSet::set,
                               BitSet::or);

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接口的组合器与重载的collect方法不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:57