I struggle with the definition and usage of the
Stream.collect(Supplier supplier, BiConsumer accumulator, BiConsumer comb
ArrayList::add
actually has 2 parameters. The ArrayList
object on which you call the add
method and the parameter to add
.
ArrayList::add
is equivalent to (list, element) -> list.add(element)
and so it works as a BiConsumer
The accumulator BiConsumer's two parameters are (1) the list itself and (2) the item to add to it. This:
List<String> asList = stringStream.collect(
ArrayList::new,
ArrayList::add,
ArrayList::addAll
);
is equivalent to this:
List<String> asList = stringStream.collect(
() -> new ArrayList<>(),
(list, item) -> list.add(item),
(list1, list2) -> list1.addAll(list2)
);
which will give the same result as this:
List<String> asList = stringStream.collect(
new Supplier<ArrayList<String>>() {
@Override
public ArrayList<String> get() {
return new ArrayList<>();
}
},
new BiConsumer<ArrayList<String>,String>() {
@Override
public void accept(ArrayList<String> list, String item) {
list.add(item);
}
},
new BiConsumer<ArrayList<String>,ArrayList<String>>() {
@Override
public void accept(ArrayList<String> list1, ArrayList<String> list2) {
list1.addAll(list2);
}
}
);