Stream类中reduce方法

reduce方法常用的有两种:

 1.reduce(BinaryOperator accumulator)

2.reduce(T identity, BinaryOperator accumulator)

package test1;

import java.io.IOException;
import java.util.*;

public class F001 {
    public static void main(String... args) throws IOException {
        double[] nums={3,2,1};

        System.out.println(Arrays.stream(nums).reduce((e1,e2)-> Math.pow(e1,e2)).getAsDouble());

        System.out.println(Arrays.stream(nums).reduce((e1,e2)-> Math.pow(e1,e2)).isPresent());

        System.out.println(Arrays.stream(nums).reduce(2,(e1,e2)-> Math.pow(e1,e2)));
    }
}

输出为:

9.0
true
64.0

前两条输出语句使用第一种用法,它接收一个自定义方法。在实例中,流中第一个元素被当作e1,第二个元素被当成e2,e1与e2计算的结果作为新的e1,紧接着读取流中下一个元素作为新的e2,以此类推,直至流中元素全部被读取。它的返回值是Optional类型的对象 (一个可能包含或不包含非空值的容器对象) ,它有两个常用的方法isPresent()(该对象中存在值时返回true,否则返回false)和get()(返回具体的值);

第三条输出语句使用第二种用法,与第一种用法相比,它多接受一个 identity 参数,并将其作为示例方法中e1的初始值。而且它的返回值为第一个参数的类型。其他细节与第一种用法类似。

你可能感兴趣的:(java,开发语言)