As stated here , the canonical way Javas implement a recursive function is a method:
public static int fib(int n) { return n==0? 0: n==1? 1: fib(n-1)+fib(n-2); }
Then, if you need an instance that executes a functional interface , you can use the method reference:
Function<Integer, Integer> fib = MyClass::fib;
or
IntUnaryOperator fib0=MyClass::fib;
This is the closest equivalent to a lambda expression, because the lambda expression is not just syntactic sugar for the generated runtime class that replaces the anonymous inner class, but also for the anonymous method, which hosts the code for a single abstract method for implementation.
Using the usual recursive method turns an anonymous method into a named one, while preserving all the other properties of lambda expressions. This is different from all other workarounds, trying to give a lambda expression a reference to itself, for example, saving an instance in a field. These workarounds are not semantically equivalent (and less efficient).
source share