2

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
szogun1987
  • 627
  • 6
  • 14
  • 3
    *"I have also taken a look for collectors, but I haven't found anything helpful."* Really?!? A web search for [`java collectors`](https://www.google.com/search?q=java+collectors) did not show any helpful articles? Such as [the javadoc of Collectors class](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html), or [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors), or [How to Use Java Stream Collectors](https://dzone.com/articles/java-stream-collectors). I find that extremely hard to believe. – Andreas May 30 '19 at 19:28
  • for someone not aware of those, you might want to add a basic description of what actually happens in that mentioned method – Eugene May 31 '19 at 09:26

1 Answers1

4

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

The Stream class has 3 reduce methods:

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:

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

Andreas
  • 154,647
  • 11
  • 152
  • 247