Argument Mismatch when using the collect Stream method

Christopher Barrett :

The following code:

names = Arrays.asList("A","B","C").stream();
List<String> namesAsList = names.collect(() -> new ArrayList<String>(),List::add,List::add);
System.out.println("Individual Strings put into a list: " + namesAsList);

generates the following error during compilation:

List namesAsList = names.collect(() -> new ArrayList(),List::add,List::add); ^ (argument mismatch; invalid method reference incompatible types: ArrayList cannot be converted to int) where R,T are type-variables: R extends Object declared in method collect(Supplier,BiConsumer,BiConsumer) T extends Object declared in interface Stream 1 error

When I amend the code to remove the generic the code compiles with an unchecked expression warning:

Stream<String> names = Arrays.asList("A","B","C").stream();
List<String> namesAsList = names.collect(() -> new ArrayList(),List::add,List::add);
System.out.println("Individual Strings put into a list: " + namesAsList);

Why would I be receiving this error? I do not expect the problem to be relating to an int.

If the answer could include the way of figuring out the issue, this will be appreciated, so I can learn how to solve these problems myself.

Grzegorz Piwowarek :

The method reference passed for combiner does not really fit. Try:

List<String> namesAsList = names
  .collect(ArrayList::new, List::add, List::addAll);

You passed the List::add and compiler is doing its best to try to interpret it as a combiner instance of BiConsumer type. Hence, the weird argument mismatch error.


Also, I assume you are implementing this only for research purposes. If you want to collect a Stream to a List, you can simply use:

.collect(Collectors.toList());

If you want to collect you Stream to ArrayList specifically, you can go for:

.collect(Collectors.toCollection(ArrayList::new));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465498&siteId=1