Search code examples
javajava-streamcollectors

Collector.of() arguments types are not resolved the way I want


Collector.of(Supplier<R> supplier, BiConsumer<R,T> accumulator, BinaryOperator<R> combiner, Function<R> finisher, Characterstics...)

    Collector<Integer, List<Integer>, List<Integer>> myCollector = 
            Collector.of(ArrayList<Integer>::new, 
                    (list, element) -> {list.add(element);}, 
                    (list1, list2) -> {list1.addAll(list2);},  
                    Function.identity();, 
                    Characteristics.values()
                    );

When I run the above code I expected the types used in the static function Collector.of() will be resolved but it wasn't. It invokes the following error in eclipse

The method of(Supplier, BiConsumer, BinaryOperator, Function, Collector.Characteristics...) in the type Collector is not applicable for the arguments (ArrayList::new, ( list, element) -> {}, ( list1, list2) -> {}, Function, Collector.Characteristics[])

I need help with this.


Solution

  • You are missing a return value in the 3rd parameter (a BinaryOperator must have a return value):

    Collector<Integer, List<Integer>, List<Integer>> myCollector = 
            Collector.of(ArrayList<Integer>::new, 
                    (list, element) -> {list.add(element);}, 
                    (list1, list2) -> {list1.addAll(list2); return list1;}, 
                                                        //  -------------   added 
                    Function.identity(), 
                    Characteristics.values()
                    );
    

    You also had an extra ; after Function.identity().