Site icon Java Guidance

Calculate factorial using stream in java ?

Calculate factorial using stream in java ?

Calculate factorial using stream in java ?

Calculate factorial using stream in java ?

In this Java code snippet, an integer variable `n` is set to 5. Using Java 8 streams, the code calculates the factorial of `n`. It does this by generating a range of integers from 1 to `n` (inclusive), and then reducing them using a multiplication operation.

The `reduce` function initializes the accumulation with 1 and iteratively multiplies each value (`a`) with the next value (`b`) in the range. The result stored in the `factorial` variable is the factorial of 5, which is 5!.


int n = 5;
int factorial = IntStream.rangeClosed(1, n)
.reduce(1, (a, b) -> a * b);

Exit mobile version