Multiple arguments:
In case of a functional interface whose method has multiple arguments, below example shows how to implement it using lambda or method reference.
This can be done using simple lambda expression where arguments have to be in brackets. Then after lambda symbol i.e. -> you can add the implementation you want.
If you already have some other API or class who has similar implementation as what functional interface needs, then you can simply pass on method reference of that already implemented method to functional interface. With this, whenever method is called on functional interface object it will delegate it to that method reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package ravi.tutorial.java.java8.lambda; public class MultiParameterMethodReferenceExample { public static void main(String[] args) { /** * Lambda way of implementing multi argument method in functional * interface. Here you provide the implementation directly i.e "a + b" */ Concatenator lambdaConcatenator = (a, b) -> a + b; System.out.println( "Lambda way = " + lambdaConcatenator.concatenate("Java", "8")); /** * Method reference way. Here you already have similar method * implemented somewhere else i.e. doSomeAppending & you just need to * re-use that implementation. Then you just use that method reference * as anonymous class. * * Parameters of Concatenator.concatenate & doSomeAppending must match. */ Concatenator methodRefConcatenator = MultiParameterMethodReferenceExample::doSomeAppending; System.out.println("Method Reference way = " + methodRefConcatenator.concatenate("Java", "8")); } public static String doSomeAppending(String one, String two) { return one + two; } } @FunctionalInterface interface Concatenator { public String concatenate(String one, String two); } |
Output:
1 2 |
Lambda way = Java8 Method Reference way = Java8 |