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


Java LongStream reduce(LongBinaryOperator op)用法及代碼示例

LongStream reduce(LongBinaryOperator op)使用關聯的累加函數對此流的元素執行約簡,並返回描述該約簡值的OptionalLong(如果有)。

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

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

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


用法:

OptionalLong reduce(LongBinaryOperator op)

參數:

  • OptionalLong:可能包含或可能不包含long值的容器對象。如果存在值,則isPresent()將返回true,而getAsLong()將返回該值。
  • LongBinaryOperator:對兩個long值操作數進行運算並產生long值結果。
  • op:用於組合兩個值的關聯無狀態函數。

返回值:描述減少值的OptionalLong(如果有)。

範例1:

// Java code for LongStream reduce 
// (LongBinaryOperator op) 
import java.util.OptionalLong; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating a LongStream 
        LongStream stream = LongStream.of(9L, 10L, 11L, 12L); 
  
        // Using OptionalLong (a container object which 
        // may or may not contain a non-null value) 
        // Using LongStream reduce(LongBinaryOperator op) 
        OptionalLong answer = stream.reduce(Long::sum); 
  
        // if the stream is empty, an empty 
        // OptionalLong is returned. 
        if (answer.isPresent()) { 
            System.out.println(answer.getAsLong()); 
        } 
        else { 
            System.out.println("no value"); 
        } 
    } 
}

輸出:

42

範例2:

// Java code for LongStream reduce 
// (LongBinaryOperator op) 
import java.util.OptionalLong; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating a LongStream 
        LongStream stream = LongStream.of(9L, 10L, 11L, 12L); 
  
        // Using OptionalLong (a container object which 
        // may or may not contain a non-null value) 
        // Using LongStream reduce(LongBinaryOperator op) 
        OptionalLong answer = stream.reduce((a, b) -> 2 * (a * b)); 
  
        // if the stream is empty, an empty 
        // OptionalLong is returned. 
        if (answer.isPresent()) { 
            System.out.println(answer.getAsLong()); 
        } 
        else { 
            System.out.println("no value"); 
        } 
    } 
}

輸出:

95040


相關用法


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