Wednesday, September 17, 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
32299 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6660 POSTS0 COMMENTS
Nicole Veronica
11833 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11895 POSTS0 COMMENTS
Shaida Kate Naidoo
6779 POSTS0 COMMENTS
Ted Musemwa
7050 POSTS0 COMMENTS
Thapelo Manthata
6735 POSTS0 COMMENTS
Umr Jansen
6741 POSTS0 COMMENTS