Java 8 Streams - collect vs reduce

前端 未结 7 1777
天涯浪人
天涯浪人 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:14

    Let the stream be a <- b <- c <- d

    In reduction,

    you will have ((a # b) # c) # d

    where # is that interesting operation that you would like to do.

    In collection,

    your collector will have some kind of collecting structure K.

    K consumes a. K then consumes b. K then consumes c. K then consumes d.

    At the end, you ask K what the final result is.

    K then gives it to you.

提交回复
热议问题