What is equivalent to Haskell scanl in Java threads?

How did python ask this question , which is equivalent to Haskell scanl in Java threads?

The best I came up with is to use

reduce(identity, accumulator, combiner) 

with a battery that saves the last result and accumulates the results in the list, although the combiner will apparently not be used. I am also not sure how to prevent its parallel use when it does not work.

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

+5
source share
1 answer

It looks like the standard Stream API has no scanl equivalent. One reason is that scanl is an operation strictly from left to right, which makes it difficult to take advantage of parallel processing (and parallel processing is an important part of the Stream API). However, you can use third-party libraries, for example, my free StreamEx library. It extends the standard Stream API by adding many more useful features, including 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 scanLeft guaranteed to work even with parallel threads, but it is unlikely that you will get acceleration if you do not have some computational intensive upstream operations that can be parallelized.

+5
source

Source: https://habr.com/ru/post/1237833/


All Articles