How to ensure the implementation of the user functional interface for using the 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); } }
Stage 1. Creation of the user functional interface
I created my own FunctionalInterface called MyCustomInterface , and in Java 8 you have to declare the interface as a functional interface using the @FunctionalInterface annotation. Now it has a single method that accepts int as param and returns int .
Step 2. Create some methods to confirm this signature.
Two methods are customMethod1 and customMethod2 , which confirm the signature of this user interface.
Step 3. Create a method that uses the functional interface ( MyCustomInterface ) as an argument
method takes an argument to MyCustomInterface .
And you are ready to go.
Stage 4: use
I mainly used method and passed it an implementation of my own methods.
method(TestingLambda::customMethod1);
source share