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 :
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream = DoubleStream.of( 2.2 , 4.3 , 6.4 ,
- 2.5 , - 4.6 );
double sumOfElements = stream.sum();
System.out.println(sumOfElements);
}
}
|
Output:
5.800000000000001
Example 2 :
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
double sumOfElements = DoubleStream.of( 2.2 , 4.2 , 6.4 ,
- 2.5 , - 4.5 )
.filter(num -> num > 2.5 )
.sum();
System.out.println(sumOfElements);
}
}
|
Output:
10.600000000000001
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
06 Dec, 2018
Like Article
Save Article