How to return lambda using Java 8?
The first thing, which I am going to show you – how you can easily return lambda as a return type. This is example is very simple and you could adjust it regarding your needs with your domain objects, etc.
We are using java.util.function.Function<T, R> interface to return function from our method. T – means input type parameter, while R – stands for object, which be returned from our lambda. In this example we take Integer as input parameter and return String from our lambda.
import java.util.function.Function; public class HelloWorld { public static void main(String[] args) { System.out.println(printAge().apply( 3 )); } static Function<Integer, String> printAge() { return (it) -> "Hello, world. My age is: " + it; } }