-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLambdaExpressions.java
More file actions
64 lines (47 loc) · 2.09 KB
/
Copy pathLambdaExpressions.java
File metadata and controls
64 lines (47 loc) · 2.09 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package java8_features;
/**
* Facilitate functional programming
* Syntax: parameter -> expression_body
* <p>
* Optional type declaration. It is infered by the compiler
* Optional paranthesis around single parameter, required for multiple parameters.
* Optional curly bracers for a sungle statement, required for multiple.
* Optional return keyword.
*/
public class LambdaExpressions {
final private static String salutation = "Hello! "; // Lambada expressions can refer to static variable
public static void main(String[] args) {
//with type declaration
MathOperation addition = (int a, int b) -> a + b; // return a + b
//with out type declaration
MathOperation subtraction = (a, b) -> a - b; // return a - b
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { // return a * b
return a * b;
};
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b; // return a / b
LambdaExpressions lambdaExpressions = new LambdaExpressions();
System.out.println("10 + 5 = " + lambdaExpressions.operate(10, 5, addition));
System.out.println("10 - 5 = " + lambdaExpressions.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + lambdaExpressions.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + lambdaExpressions.operate(10, 5, division));
//with parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
//without parenthesis
GreetingService greetService2 = (message) ->
System.out.println(salutation + message);
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
}
private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
}