欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java8的reduce使用

程序员文章站 2022-05-28 14:22:38
...
public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        //求集合元素之和
        Integer result = stream.reduce(0, Integer::sum);
        System.out.println(result);

		//求和
        stream = Arrays.stream(new Integer[]{1});
        Integer result2 = stream.reduce(0, (i, j) -> i + j);
        System.out.println("求和:" + result2);
        
        //求和
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce((i, j) -> i + j).ifPresent(System.out::println);

        //求最大值
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce(Integer::max).ifPresent(System.out::println);

        //求最小值
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce(Integer::min).ifPresent(System.out::println);

        //做逻辑运算
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);

        //求偶数的乘积
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);

        Optional.of(result2).ifPresent(System.out::println);
    }

输出:

求集合元素之和:28
求和:1
28
7
1
1
48
相关标签: Java基础