import java.util.Arrays;
import java.util.List;
public class ReduceExample {
    public static void main(String[] args) {
        // 创建一个整数列表
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        // 使用 reduce 方法计算列表中所有元素的和
        int sum = numbers.stream().reduce(0, Integer::sum);
        System.out.println("Sum: " + sum); // 输出 Sum: 15
        // 使用 reduce 方法计算列表中所有元素的乘积
        int product = numbers.stream().reduce(1, (a, b) -> a * b);
        System.out.println("Product: " + product); // 输出 Product: 120
        // 使用 reduce 方法找到列表中的最大值
        Integer max = numbers.stream().reduce(Integer.MIN_VALUE, Integer::max);
        System.out.println("Max: " + max); // 输出 Max: 5
        // 使用 reduce 方法找到列表中的最小值
        Integer min = numbers.stream().reduce(Integer.MAX_VALUE, Integer::min);
        System.out.println("Min: " + min); // 输出 Min: 1
    }
}reduce 是 Java 8 中引入的一个非常有用的方法,它用于将流中的元素组合成一个单一的结果。reduce 方法可以接受两个参数:一个是初始值,另一个是二元操作(即如何将两个元素组合在一起)。reduce 方法来计算列表中所有元素的和、乘积、最大值和最小值。Integer::sum 和 Integer::max 等是方法引用,它们简化了代码的编写。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站