How to provide custom functional interface implementation to use ::
operator
public class TestingLambda {
public static void main(String[] args) {
int value1 = method(TestingLambda::customMethod1);
int value2 = method(TestingLambda::customMethod2);
System.out.println("Value from customMethod1: " + value1);
System.out.println("Value from customMethod2: " + value2);
}
public static int customMethod1(int arg){
return arg + 1;
}
public static int customMethod2(int arg){
return arg + 2;
}
public static int method(MyCustomInterface ob){
return ob.apply(1);
}
@FunctionalInterface
interface MyCustomInterface{
int apply(int arg);
}
}
Phase 1: Create a custom functional interface
I have created my own FunctionalInterface
named MyCustomInterface
and in Java 8 you have to declare the interface to be functional interface using @FunctionalInterface
annotation. Now it has a single method taking int
as param and returning int
.
Phase 2: Create some methods confirming to that signature
Created two methods customMethod1
and customMethod2
which confirm to the signature of that custom interface.
Phase 3: Create a method that takes Functional Interface (MyCustomInterface
) as argument
method
takes MyCustomInterface
in the argument.
And you are ready to go.
Phase 4: Use
In the main I have used the method
and passed it the implementation of my custom methods.
method(TestingLambda::customMethod1);