DoubleStream reduce(DoubleBinaryOperator op)使用關聯的累加函數對此流的元素進行歸約,並返回描述縮減後的值的OptionalDouble(如果有)。
歸約運算或折疊運算采用一係列輸入元素,並將它們組合成單個匯總結果,例如查找一組數字的總和或最大值。如果滿足以下條件,則運算符或函數op是關聯的:
(a op b) op c == a op (b op c)
這是終端操作,即可能會遍曆流以產生結果或副作用。執行終端操作後,流管線被視為已消耗,無法再使用。
用法:
OptionalDouble reduce(DoubleBinaryOperator op)
參數:
- OptionalDouble:可能包含或可能不包含long值的容器對象。如果存在值,則isPresent()將返回true,而getAsDouble()將返回該值。
- DoubleBinaryOperator:對兩個雙值操作數進行運算並產生雙值結果。
- op:用於組合兩個值的關聯無狀態函數。
返回值:描述減小的值的OptionalDouble(如果有)。
範例1:
// Java code for DoubleStream reduce
// (DoubleBinaryOperator op)
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(1.2, 2.3, 3.4, 4.5);
// Using OptionalDouble (a container object which
// may or may not contain a non-null value)
// Using DoubleStream reduce(DoubleBinaryOperator op)
OptionalDouble answer = stream.reduce(Double::sum);
// if the stream is empty, an empty
// OptionalDouble is returned.
if (answer.isPresent()) {
System.out.println(answer.getAsDouble());
}
else {
System.out.println("Stream is empty");
}
}
}
輸出:
11.4
範例2:
// Java code for DoubleStream reduce
// (DoubleBinaryOperator op)
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(1.2, 2.3, 3.4, 4.5);
// Using OptionalDouble (a container object which
// may or may not contain a non-null value)
// Using DoubleStream reduce(DoubleBinaryOperator op)
OptionalDouble answer = stream.reduce((a, b)
-> (a * b) * (a * b));
// if the stream is empty, an empty
// OptionalDouble is returned.
if (answer.isPresent()) {
System.out.println(answer.getAsDouble());
}
else {
System.out.println("Stream is empty");
}
}
}
輸出:
9111992.471343633
相關用法
- Java DoubleStream of()用法及代碼示例
- Java DoubleStream sum()用法及代碼示例
- Java DoubleStream concat()用法及代碼示例
- Java DoubleStream max()用法及代碼示例
- Java DoubleStream sequential()用法及代碼示例
- Java DoubleStream min()用法及代碼示例
- Java DoubleStream toArray()用法及代碼示例
- Java DoubleStream mapToLong()用法及代碼示例
- Java DoubleStream mapToObj()用法及代碼示例
- Java DoubleStream summaryStatistics()用法及代碼示例
- Java DoubleStream iterator()用法及代碼示例
- Java DoubleStream skip()用法及代碼示例
- Java DoubleStream sorted()用法及代碼示例
- Java DoubleStream mapToInt()用法及代碼示例
- Java DoubleStream parallel()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 DoubleStream reduce(DoubleBinaryOperator op) in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。