public class LambdaFunctionVariations
1: //LambdaFunctionVariations.java
2: //Designed to illustrate some of the many variations possible when
3: //defining a lambda function, and also the way to supply a lambda
4: //function as the parameter when a method has a "functional interface"
5: //(an interface with a single abstract method) as a parameter.
6: //Note the "extra" classes that are created when the file is compiled.
8: public class LambdaFunctionVariations
9: {
10: public static void main(String args[])
11: {
12: LambdaFunctionVariations tester = new LambdaFunctionVariations();
14: //Define and then use some lambda functions:
15: //With parameter type declaration
16: MathOperation addition = (int a, int b) -> a + b;
18: //Without parameter type declaration
19: MathOperation subtraction = (a, b) -> a - b;
21: //With parameter type declaration plus return statement
22: //and curly braces
23: MathOperation multiplication = (int a, int b) ->
24: {
25: return a * b;
26: };
28: //With parameter type declaration but without return statement
29: //and without curly braces
30: MathOperation division = (int a, int b) -> a / b;
32: System.out.println();
33: System.out.println
34: (
35: "10 + 5 = "
36: + tester.operate(10, 5, addition)
37: );
38: System.out.println
39: (
40: "10 - 5 = "
41: + tester.operate(10, 5, subtraction)
42: );
43: System.out.println
44: (
45: "10 x 5 = "
46: + tester.operate(10, 5, multiplication)
47: );
48: System.out.println
49: (
50: "10 / 5 = "
51: + tester.operate(10, 5, division)
52: );
54: //With parentheses and parameter type
55: GreetingService greetService1 =
56: (String message) -> System.out.println("Hello " + message);
58: //With just parentheses
59: GreetingService greetService2 =
60: (message) -> System.out.println("Hello " + message);
62: //Without parentheses or parameter type
63: GreetingService greetService3 =
64: message -> System.out.println("Hello " + message);
66: greetService1.sayMessage("Sam");
67: greetService2.sayMessage("Mary");
68: greetService3.sayMessage("John");
69: }
71: private interface MathOperation
72: {
73: int operation
74: (
75: int a,
76: int b
77: );
78: }
80: private interface GreetingService
81: {
82: void sayMessage(String message);
83: }
85: private int operate
86: (
87: int a,
88: int b,
89: MathOperation mathOperation
90: )
91: {
92: return mathOperation.operation(a, b);
93: }
94: }
95: /* Output:
97: 10 + 5 = 15
98: 10 - 5 = 5
99: 10 x 5 = 50
100: 10 / 5 = 2
101: Hello Sam
102: Hello Mary
103: Hello John
104: */