當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java DoubleStream reduce(double identity, DoubleBinaryOperator op)用法及代碼示例


DoubleStream reduce(double identity,DoubleBinaryOperator op)使用提供的標識值和關聯的累加函數對此流的元素執行精簡,然後返回精簡的值。

歸約運算或折疊運算采用一係列輸入元素,並將它們組合成單個匯總結果,例如查找一組數字的總和或最大值。如果滿足以下條件,則運算符或函數op是關聯的:

(a op b) op c == a op (b op c)

這是終端操作,即可能會遍曆流以產生結果或副作用。執行終端操作後,流管線被視為已消耗,無法再使用。


用法:

double reduce(double identity,  DoubleBinaryOperator op)

參數:

  • identity:累加函數的標識值。
  • DoubleBinaryOperator:對兩個雙值操作數進行運算並產生雙值結果。
  • op:用於組合兩個值的關聯無狀態函數。

返回值:減少的結果。

範例1:

// Java code for DoubleStream reduce 
// (double identity, DoubleBinaryOperator op) 
import java.util.*; 
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, 5.6); 
  
        // Using DoubleStream reduce 
        // (double identity, DoubleBinaryOperator op) 
        double answer = stream.reduce(5, (num1, num2) 
                                             -> (num1 + num2)); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

輸出:

22.0

範例2:

// Java code for DoubleStream reduce 
// (double identity, DoubleBinaryOperator op) 
import java.util.*; 
import java.util.stream.DoubleStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating a DoubleStream 
        DoubleStream stream = DoubleStream.of(2.1, 3.2, 
                                              4.3, 5.4, 6.5); 
  
        // Using DoubleStream reduce 
        // (double identity, DoubleBinaryOperator op) 
        double answer = stream.reduce(3, (num1, num2) 
                                             -> (num1 * num2) * 2); 
  
        // Displaying the result 
        System.out.println(answer); 
    } 
}

輸出:

97367.96160000002


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 DoubleStream reduce(double identity, DoubleBinaryOperator op) in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。