<R> R collect(Supplier<R> supplier,
BiConsumer<R,? super T> accumulator,
BiConsumer<R,R> combiner)
Parameter 1: supplier
The get
method of the interface , which provides a container (List, Map, Set) as the parameter of the accumulator and combiner, and is the final return value (the same as the R generic constraint).
Parameter 2: accumulator
The accept
method of the interface handles the supplier The provided R type container, and the elements in the stream, such as adding elements to the container. Local aggregation of the stream.
Parameter 3: combiner
Interface accept
method to process the locally accumulator
generated R type container. Global aggregation of the local results
There are three ways to write, pay attention to the correspondence between
1. Use the implementation class example
package com;
import java.util.LinkedList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
public class App2 {
public static void main(String[] args) {
LinkedList<Integer> integers = new LinkedList<>();
integers.add(1);
integers.add(2);
integers.add(3);
List res = integers.stream().collect(
new Supplier<List>() {
@Override
public List get() {
return new LinkedList();
}
},
new BiConsumer<List, Integer>() {
@Override
public void accept(List list, Integer integer) {
list.add(integer);
}
},
new BiConsumer<List, List>() {
@Override
public void accept(List list, List list2) {
list.addAll(list2);
}
}
);
System.out.println(res);
}
}
2. Use the lambda example
package com;
import java.util.LinkedList;
import java.util.List;
public class App2 {
public static void main(String[] args) {
LinkedList<Integer> integers = new LinkedList<>();
integers.add(1);
integers.add(2);
integers.add(3);
List res = integers.stream().collect(
()->new LinkedList(),
(list, integer) -> list.add(integer),
(list1,list2) -> list1.addAll(list2)
);
System.out.println(res);
}
}
3. Use method reference
package com;
import java.util.LinkedList;
import java.util.List;
public class App2 {
public static void main(String[] args) {
LinkedList<Integer> integers = new LinkedList<>();
integers.add(1);
integers.add(2);
integers.add(3);
List res = integers.stream().collect(
LinkedList::new,
List::add,
List::addAll
);
System.out.println(res);
}
}
Reference:
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function.Supplier-java.util.function.BiConsumer-java. util.function.BiConsumer-