[英]Java Stream Reduce Method
reduce 方法在這里實際做什么? 我已經閱讀了 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;
}
看看文檔:
可選的reduce (BinaryOperator accumulator)
使用關聯累積函數對此流的元素執行縮減,並返回描述縮減值的 Optional(如果有)。
這意味着reduce
需要一個BinaryOperator<T>
- 一個特定的函數,它接受兩個T
類型的參數並生成一個具有相同類型的參數。
您的流可能有任意數量的Coder
實例, Coder
函數采用兩個Coder
並返回第二個。 這意味着,如果有任何和空的Optional
如果流首先是空的,則從整個流中返回包裝在Optional
的最后一個Coder
。
請注意,這可以更有效地編寫:
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.