Thursday, February 12, 2026
HomeLanguagesJavaLongStream sum() in Java

LongStream sum() in Java

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




// Java code for LongStream.sum() to
// find the sum of elements in LongStream
import java.util.*;
import java.util.stream.LongStream;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.of(2L, 4L, 6L, -2L, -4L);
 
        // Using LongStream.sum() to find
        // sum of elements in LongStream
        long sumOfElements = stream.sum();
 
        // Displaying the calculated sum
        System.out.println(sumOfElements);
    }
}


Output:

6

Example 2 : 

Java




// Java code for LongStream.sum() to
// find the sum of elements
// divisible by 3 in given range
import java.util.*;
import java.util.stream.LongStream;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        // Using LongStream.sum() to find
        // sum of elements divisible by 3
        // in given range
        long sumOfElements = LongStream.range(2L, 10L)
                                 .filter(num -> num % 3 == 0)
                                 .sum();
 
        // Displaying the calculated sum
        System.out.println(sumOfElements);
    }
}


Output:

18
RELATED ARTICLES

Most Popular

Dominic
32497 POSTS0 COMMENTS
Milvus
128 POSTS0 COMMENTS
Nango Kala
6869 POSTS0 COMMENTS
Nicole Veronica
11996 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12090 POSTS0 COMMENTS
Shaida Kate Naidoo
7009 POSTS0 COMMENTS
Ted Musemwa
7246 POSTS0 COMMENTS
Thapelo Manthata
6958 POSTS0 COMMENTS
Umr Jansen
6947 POSTS0 COMMENTS