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()默认也是这么实现的,所以他们两种写法是等价的。

原文地址:https://www.cnblogs.com/zhvip/p/12839019.html