Is there simplest possible reduce/fold method in java?

泄露秘密 提交于 2021-02-10 12:37:47

问题


Other technologies I know (.Net, JS) contain the simplest fold/reduce operation:

TResult reduce(TResult result, (TResult prevResult, TValue value) -> TResult)

One method I found requires TValue and TResult to be the same type. Other one requires providing BinaryOperation that combines 2 TResults. None of those constraints matches my context. For now I ended up with code like:

Accumulator acc = someInitialValue;
for(Element element: list) {
    accumulator = reducer(accumulator, element);
}

but I believe so the basic method should be contained in stream API.

I have also taken a look for collectors, but I haven't found anything helpful.


回答1:


What you're looking for is the Java Stream framework added in Java 8.

The Stream class has 3 reduce methods:

  • Optional<T> reduce(BinaryOperator<T> accumulator)
  • T reduce(T identity, BinaryOperator<T> accumulator)
  • <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)

The second reduce method matches your example, but requires same result type. For different result type, you need to use the third reduce method, which requires an extra combiner method, since it needs to support parallel processing.


It also has 2 collect methods:

  • <R,A> R collect(Collector<? super T,A,R> collector)
  • <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)

The first collect method is the most commonly used one, when used in combination with the Collectors factory class.



来源:https://stackoverflow.com/questions/56384068/is-there-simplest-possible-reduce-fold-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!