DoubleStream sum() returns the sum of elements in this stream. This is a special case of a reduction. DoubleStream 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 :
double sum()
Return Value : The function returns the sum of elements in this stream.
Note :
- If any stream element is a NaN or the sum is at any point a NaN then the sum will be NaN.
- Elements sorted by increasing absolute magnitude tend to yield more accurate result.
Example 1 :
// Java code for DoubleStream.sum() to // find the sum of elements in DoubleStream import java.util.*; import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of( 2.2 , 4.3 , 6.4 , - 2.5 , - 4.6 ); // Using DoubleStream.sum() to find // sum of elements in DoubleStream double sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); } } |
5.800000000000001
Example 2 :
// Java code for DoubleStream.sum() to // find the sum of elements // greater than 2.5 import java.util.*; import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream // Using DoubleStream.sum() to find // sum of elements greater than 2.5 double sumOfElements = DoubleStream.of( 2.2 , 4.2 , 6.4 , - 2.5 , - 4.5 ) .filter(num -> num > 2.5 ) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); } } |
10.600000000000001