Factorial of a non-negative integer n is multiplication of all integers smaller than or equal to n. In this article, we’re going to see how we can calculate factorial by using Java Stream API.

Most common implementation to calculate factorial is done by using recursion:

public int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); }

Now, lets see the approach to calculate factorial using Java Stream API.

public int factorial(int n) { IntStream stream = IntStream.rangeClosed(1, n); return stream.reduce(1, (a, b) -> a * b); }

Here, I have created an IntStream from 1 to n.

`IntStream.rangeClosed(int startInclusive, int endInclusive)`

returns a sequential ordered `IntStream`

from `startInclusive`

(inclusive) to `endInclusive`

(inclusive) by an incremental step of `1`

.

The `Stream.reduce`

method is a general-purpose reduction operation. The `reduce`

operation takes two arguments:

`identity`

: The identity element is both the initial value of the reduction and the default result if there are no elements in the stream. In this example, the identity element is 1.`accumulator`

: The accumulator function takes two parameters: a partial result of the reduction (in this example, the multiplication of all processed integers so far) and the next element of the stream . It returns a new partial result. In this example, the accumulator function is a lambda expression that multiplies two integers and returns the result:(a, b) -> a * b

## Leave a Reply