I want to convert a simple Java function to a lambda 8 function without any parameter, and then call it:
public int getMissing() {
return 0;
}
how to convert above to java8 lambda format?
A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.
The characteristics of lambda functions are: Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.
A lambda expression is characterized by the following syntax. Following are the important characteristics of a lambda expression. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
You can think of lambda expressions as anonymous methods (or functions) as they don't have a name. A lambda expression can have zero (represented by empty parentheses), one or more parameters. The type of the parameters can be declared explicitly, or it can be inferred from the context.
Your case is similar with Supplier
in Java 8
Supplier<Integer> supplier = () -> 0;
System.out.println(supplier.get());
You do not really convert methods into lambdas directly. Lambdas are more-or-less implementations of Functional Interfaces created on the fly without the overhead of the classic anonymous inner function approach.
So, if you want to pass it around as a lambda, you need to find a matching Functional Interface and assign a lambda to it.
In this case, you have a method without parameters that returns an int
and one of the possible choices would be to use IntSupplier
:
IntSupplier supplier = () -> 0;
and now, you can call it by doing:
supplier.getAsInt()
If you want to return a boxed Integer
, you would need to use a generic Supplier<T>
:
Supplier<Integer> supplier = () -> 0;
supplier.get(); // 0
It isn't clear what you intend to do with that value, but a generator has the form () -> Int
- something like,
IntStream.generate(() -> 0).limit(1).forEach(System.out::println);
If you omit the limit(1)
then you will get an infinite number of zeros, if you need to preserve order use forEachOrdered
(instead of forEach
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With