Summation of a series

The problem

In this lesson, write a program that displays the result of 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9;

Breaking it down

You could write an imperative program that loops through adding numbers or simply create a variable that will add each number together. Java 8 provides a stream reduce which is powerful stream operation. Reduce applies a function to elements of the stream in turn returning a collapsed value.

Int Stream is a specialized stream dealing with primitive ints. Next using the rangeClosed will iterate on the range of numbers between 1 and 9 inclusive. Finally calling the sum() will add each number within the stream and return a int.

public static void main(String[] args) {

    int reduceValue = IntStream.rangeClosed(1, 9).sum();