java8--- Collector.toLis() reduce

 

 

The demo found in the above-mentioned effect reduce and collect almost the same, the end result is a return, for example, we can use reduce the effect achieved toList: 

// manually implement toListCollector --- reduce abuse, not immutable statute --- parallel 
List <Integer> = servingSize, calories dishes.stream () Map (Dish :: getCalories). 
        .reduce ( new new the ArrayList <Integer> (), 
                (List <Integer> L, Integer E) -> { 
                    l.add (E ); 
                    return L; 
                }, 
                (List <Integer> L1, List <Integer> L2) -> { 
                    l1.addAll (L2); 
                    return L1; 
                } 
        );
About this practice to explain. 

<U> U the reduce (U the Identity, 
                 BiFunction <U,? Super T, U> ACC with, 
                 BinaryOperator <U> Combiner); 
U is the return value type, this is List BiFunction
<? U, Super T, U> ACC with Yes accumulator, wherein the target value and the accumulated calculation rules individual elements. Here is a List of elements and do arithmetic, eventually returned List. That is, add an element to the list. BinaryOperator <the U-> Combiner is a combiner, wherein the two target return type of a variable combined into one. Here is the list two merge. This solution has two problems: one is the semantic problem is a real problem. Semantic that, the reduce method aims to combine the two values to generate a new value, which is a reduction immutable. In contrast, the design process is to collect the container changes, whereby the integration result to output. This means that the above code fragment is
abused reduce method because it changes the List as the accumulator in place. Reduce errors semantics using the method will result in a practical problem: this reduction can not work in parallel, since by multiple threads concurrently modify the same data structure may destroy List itself. In this case, if you want thread-safe, you need every minute
With a new List, which would affect the performance object allocation. This is the reason for the variable reduction collect the container expression, the more critical it is suitable for parallel operation. Summary: reduce immutable for reduction vessel, collect the container for variable reduction. collect suitable for parallel.

Guess you like

Origin www.cnblogs.com/hahajava/p/12193298.html