How to Sum a LongStream in Java 8

By Yashwant Chavan, Views 1081, Last updated on 09-Nov-2016

This tutorial will help to learn how to use LongStream to do the sum a Long values in Java 8. rangeClosed() method returns a sequential ordered LongStream elements base on start inclusive and end inclusive.

tags java

Refer below steps.

  • LongStream.rangeClosed(long start, long end) - returns a sequential ordered LongStream from start to end (inclusive) by an incremental step of 1. Start inclusive is 1 and end inclusive is 5.
  • LongStream.reduce(LongBinaryOperator op) - performs a reduction on the elements of this stream, using an associative accumulation function and return the OptionalLong.
  • Long::sum - Define LongBinaryOperator operator, which will return sum of elements.
  • Get the value from OptionalLong.

Sum of LongStream elements



public class SumLongStream {
    public static void main(String[] args) {
        long sum = LongStream.rangeClosed(1, 5).reduce(Long::sum).getAsLong();
        System.out.println("sum:- " + sum);


sum:- 15


Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][]