...">

Argument Inconsistency when using the stream collection method

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 at compile time:

List of names AsList = names.collect (() → new ArrayList (), List :: add, list :: add); ^ (mismatch of arguments; invalid method references incompatible types: ArrayList cannot be converted to int), where R, T are type variables: R extends Object is declared in the collection method (Supplier, BiConsumer, BiConsumer) T extends Object declared in the Stream interface 1 mistake

When I fix the code to remove the common code, the code with an unverified expression warning compiles:

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 should I get this error? I do not expect the problem to be related to int.

, , .

+6
2

, combiner, . :

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

List::add, , BiConsumer. , .


, , . Stream List, :

.collect(Collectors.toList());

Stream ArrayList , :

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

combiner, : List::add List::addAll.

:

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

, , btw:

List<String> namesAsList = names.collect(
            () -> new ArrayList<>(),
            List::add,
            (List<String> left, List<String> right) -> {
                left.addAll(right);
            });

, , , () -> new ArrayList<String>(), , <String>, : () -> new ArrayList<>(). : ArrayList::new, :

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

btw - , Collectors.toList , , :

List<String> namesAsList = names.collect(Collectors.toList());

, ( List ArrayList), :

 List<String> namesAsList = names.collect(Collectors.toCollection(ArrayList::new));
+6

All Articles