gpt4 book ai didi

java - 为什么 Collector 接口(interface)的 combiner 与重载的 collect 方法不一致?

转载 作者:IT老高 更新时间:2023-10-28 20:53:15 25 4
gpt4 key购买 nike

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

<R> R collect(Supplier<R> supplier,
BiConsumer<R,? super T> accumulator,
BiConsumer<R,R> combiner)

还有另一个版本的 collect(Collector<? super T,A,R> collector) ,它接收具有前三个函数的对象。接口(interface)属性Collector对应combiner有签名BinaryOperator<A> combiner() .

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

The combiner function may fold state from one argument into the other and return that, or may return a new result container.

为什么前者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。提供您要求的“灵 active ”将使这种重载在它旨在支持的情况下变得不那么有用 - 这是当您已经拥有这些功能并且您不想让 (或学习制作)收集器只是为了收集它们。

另一方面,收集器具有更广泛的用途,因此具有额外的灵 active 。

关于java - 为什么 Collector 接口(interface)的 combiner 与重载的 collect 方法不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com