Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Haskell's scanl in Java's streams?

As this question asked for python, what is the equivalent of Haskell's scanl in Java's streams?

The best I've come up with so far is to use

reduce(identity, accumulator, combiner)

with an accumulator that keeps the latest result and accumulates the results in a list, though the combiner would presumably not be not used. I'm also not sure how to prevent it from being used in parallel, where it would not work.

Perhaps Stream is the wrong interface for (an equivalent of) scanl?

like image 459
Graeme Moss Avatar asked Dec 10 '15 09:12

Graeme Moss


1 Answers

Looks like standard Stream API has no scanl equivalent. One of the reasons is the fact that scanl is strictly left-to-right operation which makes it hard to have benefits from parallel processing (and parallel processing is an important part of Stream API). You may however use third-party libraries like my free StreamEx library. It extends standard Stream API adding many more useful functions including the scanLeft:

List<Integer> list = IntStreamEx.range(10).boxed().scanLeft(Integer::sum);
System.out.println(list);
// outputs [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

This scanLeft operation is guaranteed to work even with parallel streams, but you're unlikely to have the speedup unless you have some computational intensive upstream operations which could be parallelized.

like image 198
Tagir Valeev Avatar answered Sep 19 '22 13:09

Tagir Valeev