Write a Java program using Lambda Expression to calculate the factorial of a given number


The java program that calculates the factorial of a given number using a lambda expression and the IntUnaryOperator functional interface. Here's an explanation of the code:

  • import java.util.function.IntUnaryOperator;: This line imports the IntUnaryOperator functional interface from the java.util.function package. The IntUnaryOperator interface represents a function that accepts an integer input and produces an integer result.
  • The Factorial class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • int number = 5;: This line sets the value of the number variable to 5, which is the number for which you want to calculate the factorial.
    • IntUnaryOperator factorial = n -> { ... };: This line defines an IntUnaryOperator named factorial using a lambda expression. The lambda expression takes an integer n and calculates the factorial of n using a loop.
      • It initializes a result variable to 1.
      • It uses a for loop to calculate the factorial by multiplying the result by numbers from 1 to n.
      • Finally, it returns the calculated factorial as the result.
    • int fact = factorial.applyAsInt(number); : This line applies the factorial lambda expression to the number by using the applyAsInt method of the IntUnaryOperator. It calculates the factorial and stores the result in the fact variable.
    • System.out.println("Factorial of " + number + " : " + fact);: This line prints the calculated factorial of the number.

Source Code

import java.util.function.IntUnaryOperator;
public class Factorial
{
	public static void main(String[] args)
	{
		int number = 5;
 
		IntUnaryOperator factorial = n -> {
			int result = 1;
			for (int i = 1; i <= n; i++)
			{
				result *= i;
			}
			return result;
		};
 
		int fact = factorial.applyAsInt(number);
 
		System.out.println("Factorial of " + number + " : " + fact);
	}
}

Output

Factorial of 5 : 120

Example Programs