Java mapToInt vs Reduce with map

前端 未结 2 915
长发绾君心
长发绾君心 2021-01-18 23:14

I\'ve been reading up on reduce and have just found out that there is a 3 argument version that can essentially perform a map reduce like this:

String[] stra         


        
2条回答
  •  执念已碎
    2021-01-19 00:17

    The three-argument Stream.reduce is more flexible:

     U reduce(U identity,
                 BiFunction accumulator,
                 BinaryOperator combiner);
    

    in comparison with the two-argument IntStream.reduce that accepts and returns only int values:

    int reduce(int identity, IntBinaryOperator op);
    

    While accumulator in the three-argument version can accept parameters of two different types:

    BiFunction acc = (i, str) -> i + str.length();
    

    that allows you to omit additional map operation:

    Arrays.stream(strs).reduce(0, (i, str) -> i + str.length(), Integer::sum)
    

提交回复
热议问题