LongStream sum() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 28-Mar-2019 12:24:35
Advertisements