LongStream sum() in Java
Last Updated :
25 May, 2022
LongStream sum() returns the sum of elements in this stream. This is a special case of a reduction. LongStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers.
Syntax :
long sum()
Return Value : The function returns the sum of elements in this stream.
Example 1 :
Java
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(2L, 4L, 6L, -2L, -4L);
long sumOfElements = stream.sum();
System.out.println(sumOfElements);
}
}
|
Example 2 :
Java
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
long sumOfElements = LongStream.range(2L, 10L)
.filter(num -> num % 3 == 0 )
.sum();
System.out.println(sumOfElements);
}
}
|
Share your thoughts in the comments
Please Login to comment...