Java - Recursive Lambda Expressions

Introduction

A lambda expression does not support recursive invocations.

To create recursive lambda, use a method reference or an anonymous inner class.

The following code uses a method reference to create a recursive lambda expression.

It defines a recursive method called factorial() that computes the factorial of an integer.

In the main() method, it uses the method reference RecursiveTest::factorial in place of a lambda expression.

Demo

import java.util.function.IntFunction;

public class Main {
  public static void main(String[] args) {
    IntFunction<Long> factorialCalc = Main::factorial;

    int n = 5;/*w w w  .j a  va 2 s.  c om*/
    long fact = factorialCalc.apply(n);
    System.out.println("Factorial of " + n + " is " + fact);
  }

  public static long factorial(int n) {
    if (n < 0) {
      String msg = "Number must not be negative.";
      throw new IllegalArgumentException(msg);
    }

    if (n == 0) {
      return 1;
    } else {
      return n * factorial(n - 1);
    }
  }
}

Result

Related Topics