I would like pass a function as an parameter to another function. For example:
void myFunction(boolean coondition, void function())
{
if(condition) {
function();
}
}
It this possible in Java 8?
I would like pass a function as an parameter to another function. For example:
void myFunction(boolean coondition, void function())
{
if(condition) {
function();
}
}
It this possible in Java 8?
In Java, quite everything is an object (but primitive types). But you can use functional interfaces to handle functions. Before Java 8, there was already use-cases where functional interfaces were used often through the instantiation of anonymous classes:
If you want to pass a function as a parameter, you have many ways to express that:
Let's say you want to apply some function (e.g. square a value) if some condition is met on the initial value (e.g. this is an even number):
You can test it:
And this can also be written with lambdas:
Or directly:
And you can also use member methods as functions, provided they have a functional interface signature.
Test it on a list of 10 Foo objects:
Which can be shortened to:
Yes, it is possible. Assuming your function does nothing, just pass a
Runnable
.Assuming you have a function named
function
as such (void
can be replaced by a return type, which will not be used):you can call it like this using lambda expressions
or like this in Java 1.1-1.7
No, you can't pass methods.
But there is a simple workaround: pass a Runnable.
and call it like this: (using the old syntax)
or using the new lambda syntax in Java 8 (which is mostly shorthand for the above):