Saturday, September 6, 2025
HomeLanguagesJavaDoubleStream sum() in Java

DoubleStream sum() in Java

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 :

  1. If any stream element is a NaN or the sum is at any point a NaN then the sum will be NaN.
  2. 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);
    }
}


Output:

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);
    }
}


Output:

10.600000000000001
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS