简体   繁体   中英

Java Stream Reduce Method

What is the reduce method actually doing here? I've read the Oracle docs but I still don't understand what the reduce method is doing here in this example

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)

Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

This means reduce takes a BinaryOperator<T> - a specific function that takes two parameters of type T and produces one with the same type.

You stream might have any number of Coder instances, the reducing function takes two Coder s and returns the second one. 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.

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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