<R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
Collect,收集采集的意思。就是把流(stream)中的结果数据保存到集合或数组中去。
看例子:
void stream_collect() {
Stream<String> stream = Stream.of("I","love","you","too","\n");
ArrayList<String> list = stream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
list.forEach(System.out::print);
Stream<String> stream1 = List.of("I","love","you").stream();
//String str = stream1.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
String str = stream1.collect(StringBuffer::new, StringBuffer::append, StringBuffer::append).toString();
System.out.println(str);
}
这里遇到一个问题,当使用String类型参数的时候无法正确执行,代码如下:
String str = stream1.collect(String::new, (a,b) -> a = a.concat(b), (a,b) -> a = a.concat(b));
以上代码执行结果为空,why?后面有时间再研究一下。
<R,A> R collect(Collector<? super T,A,R> collector)
这个方法功能太强大了,特别是配合Collectors使用,基本上可以覆盖大部分需求。
Collectors的使用可以参看Collectors学习文档。