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:

/**
 * 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:

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:

/**
 * 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:

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:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts