In this tutorial, we will see “How to find the ‘FACTORIAL’ of an Integer using Java 8?” find factorial of integer using java 8
Java 8 – How to find ‘FACTORIAL’ of an Integer? Share on X
Java 8 method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /** * Find 'Factorial' of an Integer using Java 8 * @author Deepak Verma * */ import java.util.stream.LongStream; public class Find_Factorial_of_Integer_Java8_Example { public static void main(String[] args) { // Find the factorial of 5 long factorial = LongStream.rangeClosed(1, 5) .reduce(1, (long x, long y) -> x * y); System.out.println("Factorial of 5: "+factorial); } } |
Output:
1 | Factorial of 5: 120 |
find factorial of integer using java 8
This particular example uses the rangeClosed
method of the LongStream
class to generate a stream of integers ranging from 1 to 5, inclusive. Then, it uses the reduce
method to perform a reduction on the stream, multiplying each element by the accumulator which is initially set to 1. Finally, the result of the reduction is the factorial of 5.
Traditional Java method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** * Find 'Factorial' of an Integer using Java (Before 8) * @author Deepak Verma * */ package org.java8.examples; public class Find_Factorial_of_Integer_Java_Example { public static void main(String[] args) { // Find the factorial of 5 System.out.println("Factorial of 5: "+factorial(5)); } public static long factorial(long n) { if (n == 1) return 1; else return (n * factorial(n - 1)); } } |
Output:
1 | Factorial of 5: 120 |
remove whitespaces from string in java
skip method java 8 stream
Java 8 – How to find ‘FACTORIAL’ of an Integer? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: