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


Java LongStream sum()用法及代碼示例


LongStream sum()返回此流中的元素之和。這是減少的特殊情況。 LongStream sum()是一種終端操作,即,它可以遍曆流以產生結果或副作用。

注意:歸約運算(也稱為折疊)采用一係列輸入元素,並通過重複應用組合運算(例如,找到一組數字的總和或最大值)將它們組合成單個匯總結果。

用法:


long sum()

返回值:該函數返回此流中元素的總和。

示例1:

// Java code for LongStream.sum() to 
// find the sum of elements in LongStream 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating an LongStream 
        LongStream stream = LongStream.of(2L, 4L, 6L, -2L, -4L); 
  
        // Using LongStream.sum() to find 
        // sum of elements in LongStream 
        long sumOfElements = stream.sum(); 
  
        // Displaying the calculated sum 
        System.out.println(sumOfElements); 
    } 
}
輸出:
6

示例2:

// Java code for LongStream.sum() to 
// find the sum of elements 
// divisible by 3 in given range 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Using LongStream.sum() to find 
        // sum of elements dividible by 3 
        // in given range 
        long sumOfElements = LongStream.range(2L, 10L) 
                                 .filter(num -> num % 3 == 0) 
                                 .sum(); 
  
        // Displaying the calculated sum 
        System.out.println(sumOfElements); 
    } 
}
輸出:
18


相關用法


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