LongStream sum() method in Java


The sum() method of the LongStream class returns the sum of elements in this stream.

The syntax is as follows

long sum()

To use the LongStream class in Java, import the following package

import java.util.stream.LongStream;

First, create an IntStream and add some elements

LongStream longStream = LongStream.of(100L, 30000L, 45000L, 55000L, 70000L);

Now, add the elements of the stream

long res = longStream.sum();

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

Example

 Live Demo

import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.of(100L, 30000L, 45000L, 55000L, 70000L);
      long res = longStream.sum();
      System.out.println("The sum of elements in the stream = "+res);
   }
}

Output

The sum of elements in the stream = 200100

Updated on: 30-Jul-2019

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements