java – Java 8 stream

Normal reduction is meant to combine two immutable values like int, double etc. And produce a new one; it is a reduction immutable . On the contrary, the collection method is designed for change a container to accumulate the result it should produce.

To illustrate the problem, let’s assume you want to get Collectors.toList() using a simple reduction as below

    List numbers = stream.reduce( new ArrayList(), 
    (List l, Integer e) -> {
     l.add(e); 
     return l; 
    },
     (List l1, List l2) -> { 
    l1.addAll(l2); return l1; });

This is the equivalent of Collectors.toList(). However, in this case change theList. As we know, ArrayList it is not thread safe, nor can you add / remove values ​​from it during iteration, so you get a concurrent exception or arrayIndexOutBound exception or any kind of exception (especially if executed in parallel) when updating the list or combinator tries to merge lists because you are editing the list by accumulating (adding) integers to it. If you want to make this thread safe you have to pass a new list each time which would affect performance.

On the contrary, the Collectors.toList() it works in a similar way. However, it ensures thread safety when accumulating values ​​in the list. From the documentation for the method collect:

Performs a mutable reduce operation on the elements of this stream using a Collector. If the stream is parallel and the Collector is simultaneous and the stream is not sorted or the collector is not sorted, a simultaneous reduction will be performed. When run in parallel, multiple intermediate results can be instantiated, compiled, and merged to maintain the isolation of mutable data structures. Therefore, even when running in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is required for parallel reduction. link =

So to answer your question:

When would you use collect() vs reduce()?

if you have immutable values ​​like ints, doubles, Strings the normal reduction works well. However, if you have to reduce your values ​​to say a List (mutable data structure), then you need to use mutable reduction by method collect.

Leave a comment