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

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

    If the former collect method receive a BinaryOperator then the following example would not compile:

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

    In this case the compiler could not infer the return type of the combiner and would give a compilation error.

    So if this version of collect method was consistent with the Collector interface then it would promote a more complex use of this version of collect method, that was not intended.

提交回复
热议问题