Java mapToInt vs Reduce with map

前端 未结 2 927
长发绾君心
长发绾君心 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:14

    Is one better than the other, and if so, why?

    With the first reduce approach there’s an insidious boxing cost.

    The mapToInt.reduce(...) approach avoids that.

    So, the idea is if you're interested in summation, average et al just use the primitive stream specializations as they're more efficient.

    By the way, the code:

    Arrays.stream(strarr).mapToInt(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2)
    

    can be simplified to:

    Arrays.stream(strarr).mapToInt(s -> s.length()).sum();
    

提交回复
热议问题