java8 stream的reduce()方法

reduce是用来执行聚合操作的。
参数BinaryOperator接口继承了BiFunction接口,简单的说就是
传入2个参数,返回一个参数。 2个入参,和一个出参类型都相同。
直接上代码:

@Data
public class User {

    private String username;
    private String password;
    private Integer age;
    public User(){

    }

    public User(String username, String password, Integer age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public static void main(final String... args) {
        ArrayList<User> list = new ArrayList<>();

        list.add(new User("liubei","111",40));
        list.add(new User("zhangfei","222",30));
        list.add(new User("guanyu","333",35));

        //reduce 需要传入一个BinaryOperator接口,继承了BiFunction接口
        //简单说  就是需要传入2个同类型参数,返回同类型的参数
        BinaryOperator<Integer> add = (n1, n2) -> n1+n2;
        BinaryOperator<Integer> minus = (n1, n2) -> n1-n2;
        list.stream().map(n->n.getAge()).reduce((a,b)->a*b).ifPresent(n-> System.out.println(n)); // 乘法
        list.stream().map(n->n.getAge()).reduce(add).ifPresent(n-> System.out.println(n)); // 加法
        list.stream().map(n->n.getAge()).reduce(minus).ifPresent(n-> System.out.println(n)); // 减法

    }
}

你可能感兴趣的:(java)