zoukankan      html  css  js  c++  java
  • Collectors.toList()的理解

    Collectors.toList()用来结束Stream流。

        public static void main(String[] args) {
    
            List<String> list = Arrays.asList("hello","world","stream");
            list.stream().map(item->item+item).collect(Collectors.toList()).forEach(System.out::println);
            list.stream().map(item->item+item).collect(
                    ArrayList::new,
                    (list1,value )-> list1.add(value),
                    (list1 ,list2)-> list1.addAll(list2)
                    ).forEach(System.out::println);
    
        }
        <R> R collect(Supplier<R> supplier,
                      BiConsumer<R, ? super T> accumulator,
                      BiConsumer<R, R> combiner);

    从文档上我们可以知道,collect()方法接收三个函数式接口

    • supplier表示要返回的类型,Supplier<R> supplier不接收参数,返回一个类型,什么类型,这里是ArrayList类型,所以是ArrayList::new
    • BiConsumer<R, ? super T> accumulator接收两个参数,一个是返回结果(ArrayList),一个是stream中的元素,会遍历每一个元素,这里要做的是把遍历的每一个元素添加到要返回的ArrayList中,所以第二个参数(list1,value )-> list1.add(value),
    • BiConsumer<R, R> combiner接收两个参数,一个是返回结果,一个是遍历结束后得到的结果,这里要把遍历结束后得到的list添加到要返回的list中去,所以第三个参数是,(list1 ,list2)-> list1.addAll(list2)
     
        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);
        }

    我们可以看到,Collectors.toList()默认也是这么实现的,所以他们两种写法是等价的。

  • 相关阅读:
    扩展正则表达式 练习题
    Linux特殊符号
    文件属性下
    文件属性和ls -lhi
    复习之前的和补充一些内容
    第二关练习题总结完结
    云服务器防ssh攻击
    实验四+085
    实验3+085
    第5次作业+085
  • 原文地址:https://www.cnblogs.com/zhvip/p/12839019.html
Copyright © 2011-2022 走看看