snippetjavaCritical
How do I define a method which takes a lambda as a parameter in Java 8?
Viewed 0 times
takeshowjavaparametermethoddefinelambdawhich
Problem
In Java 8, methods can be created as Lambda expressions and can be passed by reference (with a little work under the hood). There are plenty of examples online with lambdas being created and used with methods, but no examples of how to make a method taking a lambda as a parameter. What is the syntax for that?
MyClass.method((a, b) -> a + b);
class MyClass{
//How do I define this method?
static int method(Lambda l) {
return l(5, 10);
}
}
Solution
Lambdas are purely a call-site construct: the recipient of the lambda does not need to know that a Lambda is involved, instead it accepts an Interface with the appropriate method.
In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.
Since Java 8 there is a set of commonly-used interface types in
For this specific use case there's
But you can just as well define your own interface and use it like this:
Then call the method with a lambda as parameter:
Using your own interface has the advantage that you can have names that more clearly indicate the intent.
In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.
Since Java 8 there is a set of commonly-used interface types in
java.util.function.For this specific use case there's
java.util.function.IntBinaryOperator with a single int applyAsInt(int left, int right) method, so you could write your method like this:static int method(IntBinaryOperator op){
return op.applyAsInt(5, 10);
}But you can just as well define your own interface and use it like this:
public interface TwoArgIntOperator {
public int op(int a, int b);
}
//elsewhere:
static int method(TwoArgIntOperator operator) {
return operator.op(5, 10);
}Then call the method with a lambda as parameter:
public static void main(String[] args) {
TwoArgIntOperator addTwoInts = (a, b) -> a + b;
int result = method(addTwoInts);
System.out.println("Result: " + result);
}Using your own interface has the advantage that you can have names that more clearly indicate the intent.
Code Snippets
static int method(IntBinaryOperator op){
return op.applyAsInt(5, 10);
}public interface TwoArgIntOperator {
public int op(int a, int b);
}
//elsewhere:
static int method(TwoArgIntOperator operator) {
return operator.op(5, 10);
}public static void main(String[] args) {
TwoArgIntOperator addTwoInts = (a, b) -> a + b;
int result = method(addTwoInts);
System.out.println("Result: " + result);
}Context
Stack Overflow Q#13604703, score: 337
Revisions (0)
No revisions yet.