IntStream sum() returns the sum of elements in this stream. This is a special case of a reduction. IntStream 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 :
int sum()
Return Value : The function returns the sum of elements in this stream.
Example 1 :
// Java code for IntStream.sum() to // find the sum of elements in IntStream import java.util.*; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, -2, -4); // Using IntStream.sum() to find // sum of elements in IntStream int sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); } } |
6
Example 2 :
// Java code for IntStream.sum() to // find the sum of elements // divisible by 3 in given range import java.util.*; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Using IntStream.sum() to find // sum of elements dividible by 3 // in given range int sumOfElements = IntStream.range(2, 10) .filter(num -> num % 3 == 0) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); } } |
18
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- java.util.stream.IntStream/LongStream | Search an element
- IntStream iterator() in Java
- IntStream rangeClosed() in Java
- IntStream map(IntUnaryOperator mapper) in Java
- IntStream findFirst() in Java
- IntStream parallel() in Java
- IntStream empty() in Java with examples
- IntStream distinct() in Java with examples
- IntStream peek() in Java with examples
- IntStream average() in Java with Examples
- IntStream max() in Java with examples
- IntStream min() in Java with Examples
- IntStream count() in Java with examples
- IntStream skip() in Java
- IntStream filter() in Java with examples
- IntStream concat() in Java
- IntStream anyMatch() in Java with examples
- IntStream allMatch() in Java with examples
- IntStream generate() method in Java
- IntStream summaryStatistics() in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

