Java新特性玩转JDK8之collector收集器

DBC 1.6K 0
collect()⽅法的作⽤

⼀个终端操作, ⽤于对流中的数据进⾏归集操作,collect⽅法接受的参数是⼀个Collector
有两个重载⽅法,在Stream接⼝⾥⾯

 //重载⽅法⼀
 <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提供了很多⼯⼚⽅法

Collectors 的作⽤

⼯具类,提供了很多常⻅的收集器实现

Collectors.toList()
public static <T> Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>)
ArrayList::new, List::add,(left, right) -> {
left.addAll(right); return left; }, CH_ID);
}
ArrayList::new,创建⼀个ArrayList作为累加器
List::add,对流中元素的操作就是直接添加到累加器中
reduce操作, 对⼦任务归集结果addAll,后⼀个⼦任务的结果直接全部添加到
前⼀个⼦任务结果中
CH_ID 是⼀个unmodifiableSet集合
Collectors.toMap()
Collectors.toSet()
Collectors.toCollection() :⽤⾃定义的实现Collection的数据结构收集

Collectors.toCollection(LinkedList::new)
Collectors.toCollection(CopyOnWriteArrayList::new)
Collectors.toCollection(TreeSet::new)

小例子
        List<String> list = Arrays.asList("sdfsdf","xxxx","bbb","bbb");

        //List<String> results = list.stream().collect(Collectors.toList());
        //list.stream().collect(Collectors.toSet());
        //List<String> result = list.stream().collect(Collectors.toCollection(LinkedList::new));

        List<String> result = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));

        Set<String> stringSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
        System.out.println(result);
        System.out.println(stringSet);
控制台输出Java新特性玩转JDK8之collector收集器插图

发表评论 取消回复
表情 图片 链接 代码

分享