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

后端 未结 3 1677
情歌与酒
情歌与酒 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:33

    The "inline" (3-arg) version of collect is designed for when you already have these functions "lying around". For example:

    ArrayList list = stream.collect(ArrayList::new, 
                                         ArrayList::add,
                                         ArrayList::addAll);
    

    Or

    BitSet bitset = stream.collect(BitSet::new, 
                                   BitSet::set,
                                   BitSet::or);
    

    While these are just motivating examples, our explorations with similar existing builder classes was that the signatures of the existing combiner candidates were more suited to conversion to BiConsumer than to BinaryOperator. Offering the "flexibility" you ask for would make this overload far less useful in the very cases it was designed to support -- which is when you've already got the functions lying around, and you don't want to have to make (or learn about making) a Collector just to collect them.

    Collector, on the other hand, has a far wider range of uses, and so merits the additional flexibility.

提交回复
热议问题