Java 8 Streams - collect vs reduce

前端 未结 7 1753
天涯浪人
天涯浪人 2020-11-28 01:17

When would you use collect() vs reduce()? Does anyone have good, concrete examples of when it\'s definitely better to go one way or the other?

7条回答
  •  失恋的感觉
    2020-11-28 02:09

    Here is the code example

    List list = Arrays.asList(1,2,3,4,5,6,7);
    int sum = list.stream().reduce((x,y) -> {
            System.out.println(String.format("x=%d,y=%d",x,y));
            return (x + y);
        }).get();
    

    System.out.println(sum);

    Here is the execute result:

    x=1,y=2
    x=3,y=3
    x=6,y=4
    x=10,y=5
    x=15,y=6
    x=21,y=7
    28
    

    Reduce function handle two parameters, the first parameter is the previous return value int the stream, the second parameter is the current calculate value in the stream, it sum the first value and current value as the first value in next caculation.

提交回复
热议问题