Why is the combiner of the Collector interface not consistent with the overloaded collect method?

后端 未结 3 1676
情歌与酒
情歌与酒 2021-02-12 11:27

There is an overload method, collect(), in interface Stream with the following signature:

 R collect(Supplier

        
3条回答
  •  感情败类
    2021-02-12 11:44

    Keep in mind that the primary purpose of Stream.collect() is to support Mutable Reduction. For this operation, both functions, the accumulator and the combiner are meant to manipulate the mutable container and don’t need to return a value.

    Therefore it is much more convenient not to insist on returning a value. As Brian Goetz has pointed out, this decision allows to re-use a lot of existing container types and their methods. Without the ability to use these types directly, the entire three-arg collect method would be pointless.

    In contrast, the Collector interface is an abstraction of this operation supporting much more use cases. Most notably, you can even model the ordinary, i.e. non-mutable, Reduction operation with value types (or types having value type semantics) via a Collector. In this case, there must be a return value as the value objects themselves must not be modified.

    Of course, it is not meant to be used as stream.collect(Collectors.reducing(…)) instead of stream.reduce(…). Instead, this abstraction comes handy when combining collectors, e.g. like groupingBy(…,reducing(…)).

提交回复
热议问题