java8学习笔记(四):强大的collect浅析

502 阅读1分钟

引言

前面几篇文章,我们了解了Stream的常用使用方式 时空隧道,但该部分更多的是涉及数据过滤,Stream更加强大之处在于对数据的聚合操作,能变为任意你想要的数据结构。

总览

我们先看看源码中对collect()方法的定义:

<R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner);

<R, A> R collect(Collector<? super T, A, R> collector);

第一种入参明确,为简易版本,第二种用法更为高级,复杂的操作都封装到Collector接口中,为流式操作提供了无限可能。通常配合Collectors类使用,该类中提供诸多静态方法供使用者调用。都说香烟配酒,天下我有。那么接下来且听我慢慢道来 ...

本文中初始化集合数据均可参考前文 时空隧道 !

Collector<T, ?, C> toCollection(Supplier collectionFactory)

返回指定的集合列表,如LinkedList等;我们来看示例:

List<Cat> toCollectionMethodList = catList.stream().limit(3).collect(toCollection(LinkedList::new));
toCollectionMethodList.stream().forEach(System.err::println);

result:

Cat{age=4, cnName='七夕', enName='seventh', isMale=true}
Cat{age=3, cnName='曾三妹', enName='sisterThree', isMale=false}
Cat{age=2, cnName='奶酪', enName='cheese', isMale=true}

Collector<T, ?, List> toList()

默认返回ArrayList集合

List<Cat> toListMethodList = catList.stream().skip(2).collect(toList());
toListMethodList.stream().forEach(System.err::println);

result:

Cat{age=2, cnName='奶酪', enName='cheese', isMale=true}
Cat{age=2, cnName='奶油', enName='cream', isMale=true}