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