Syntax error IntStream sum() method in Java

IntStream sum() method in Java



The sum() method of the IntStream class is used in Java to return the sum of elements in this stream.

The syntax is as follows −

int sum()

To work with the IntStream class in Java, import the following package −

import java.util.stream.IntStream;

Create IntStream and add some elements −

IntStream intStream = IntStream.of(50, 100, 150, 200, 250, 300);

Now, return the sum of elements in the IntStream added above −

int sumVal = intStream.sum();

The following is an example to implement IntStream sum() method in Java −

Example

 Live Demo

import java.util.stream.IntStream;

public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(50, 100, 150, 200, 250, 300);
      int sumVal = intStream.sum();
      System.out.println("Sum of elements in the stream = "+sumVal);
   }
}

Output

Sum of elements in the stream = 1050
Updated on: 2019-07-30T22:30:25+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements