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
下一篇: 华为不想做下一个英特尔 但计算野心尽露