简体   繁体   English

Java Stream Reduce 方法

[英]Java Stream Reduce Method

What is the reduce method actually doing here? reduce 方法在这里实际做什么? I've read the Oracle docs but I still don't understand what the reduce method is doing here in this example我已经阅读了 Oracle 文档,但我仍然不明白这个例子中的 reduce 方法在做什么

public static Coder findCoderWithWorstBMI(List<Coder> coders) {
    return coders.stream().sorted(Comparator.comparing(BMICalculator::calculateBMI))
            .reduce((first, second) -> second).orElse(null);
}

private static double calculateBMI(Coder coder) {
    double height = coder.getHeight();
    double weight = coder.getWeight();
    if (height == 0.0)
        throw new ArithmeticException();
    double bmi = weight / (height * height);
    return Math.round(bmi * 100) / 100.0;
}

Take a look at the documentation :看看文档

Optional reduce​(BinaryOperator accumulator)可选的reduce (BinaryOperator accumulator)

Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.使用关联累积函数对此流的元素执行缩减,并返回描述缩减值的 Optional(如果有)。

This means reduce takes a BinaryOperator<T> - a specific function that takes two parameters of type T and produces one with the same type.这意味着reduce需要一个BinaryOperator<T> - 一个特定的函数,它接受两个T类型的参数并生成一个具有相同类型的参数。

You stream might have any number of Coder instances, the reducing function takes two Coder s and returns the second one.您的流可能有任意数量的Coder实例, Coder函数采用两个Coder并返回第二个。 This means, that from the whole stream the last Coder wrapped in Optional is returned if there are any and empty Optional if the stream was empty in the first place.这意味着,如果有任何和空的Optional如果流首先是空的,则从整个流中返回包装在Optional的最后一个Coder

Note, that this can be written more efficiently:请注意,这可以更有效地编写:

coders.stream()
    .max(Comparator.comparing(BMICalculator::calculateBMI))
    .orElse(null);
.reduce((first, second) -> second).orElse(null);

如果存在第一个和第二个值,reduce 方法将执行其他 orElse(null) 接受 null 将返回 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM