This is the fifth solution to find the factorial of a number using Stream. This program uses the LongStream, range(), reduce() methods.
import java.util.Scanner;
import java.util.stream.LongStream;
public class FactorialUsingStreams {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner inpInt = new Scanner(System.in);
System.out.print("Enter a number= ");
int numValue = inpInt.nextInt();
System.out.println(
"Factorial of " + numValue + " is " + LongStream.range(1, numValue + 1).reduce(1, (a, b) -> (a * b)));
}
}
OUTPUT-
Enter a number= 9
Factorial of 9 is 362880

Leave a comment