Java8 lambda reduce解析

1.Optional<T> reduce(BinaryOperator<T> accumulator);

@org.junit.Test
    public void test(){
        Boolean[] arr = {false,false};
        List<Boolean> list = Arrays.asList(arr);
        Boolean aBoolean = list.stream().reduce((one, two) -> one || true).get();
        System.out.println("final" + aBoolean);
    }

解析:

reduce后面的(one,two)为传入的两个参数,分别代表list中的第一个和第二个value,

然后执行运算one||two,返回值赋给one,此时的two为list的第三个value,

... ...

直至遍历完list中的所有的值,最后的值为函数最终返回值,此时函数返回值为Optional类型,通过.get()获取最终的值;

注意:

若list中没有元素,会报错的:  java.util.NoSuchElementException: No value present

为了避免这种情况发生:

 @org.junit.Test
    public void test(){
        Boolean[] arr = {};
        List<Boolean> list = Arrays.asList(arr);
        Boolean aBoolean = list.stream().reduce((one, two) -> one || true).orElse(true);
        System.out.println("final" + aBoolean);
    }

orElse(true)的作用就是当list为空时返回这里面的值;

2.T reduce(T identity, BinaryOperator<T> accumulator);

     显而易见,相比于1多了一个参数  T identity,而且函数返回值为T,与我们传参类型是一致的,说明该函数无需调用get()从Operator中取最终值了;

    使用方法也很简单,多传的一个参数为初始值,可以理解为在独立集合之外的可以传一个参数参与运算,或者理解为该初始值为了避免传入的集合为空集合,再调用orElse()返回默认值;

  @org.junit.Test
    public void test(){
        Integer[] arr = {2};
        List<Integer> list = Arrays.asList(arr);
        Integer aBoolean = list.stream().reduce(1,(one, two) -> {
            System.out.println(one);
            System.out.println(two);
            return one + two;
        });
        System.out.println("final -> " + aBoolean);
    }

执行时,先把初始值赋给one,再从list中取第一个元素赋给two,执行one+two,结果赋给one

然后再从list中取第二个元素赋给two,再运算one+two,赋给one;

直至遍历完list,最终值返回;

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

还没研究明白,若有人通透请补充评论区;等我研究通透再完善;

猜你喜欢

转载自my.oschina.net/u/3220575/blog/1826170