- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleLambda.java
More file actions
Latest commit
70 lines (57 loc) · 2.2 KB
/
Copy pathSimpleLambda.java
File metadata and controls
70 lines (57 loc) · 2.2 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
65
66
67
68
69
70
packageexamples;
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.Comparator;
importjava.util.List;
publicclassSimpleLambda {
publicstaticvoidmain(String[] args) {
// ----------------Comparator example--------------
// Traditional way
Comparator<String> c1 = newComparator<String>() {
@Override
publicintcompare(Strings1, Strings2) {
returnInteger.compare(s1.length(), s2.length());
}
};
// Lambda way
Comparator<String> c2 = (Strings1, Strings2) -> Integer.compare(s1.length(), s2.length());
//call the comparator by c2.compare("strign1", "string2");
// ----------------Collections sorting example--------------
List<String> names = Arrays.asList("John", "Smith", "Paul");
// Traditional way
Collections.sort(names, newComparator<String>() {
@Override
publicintcompare(Stringo1, Stringo2) {
returno1.compareTo(o2);
}
});
// Lambda way
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
// ----------------Runnable example--------------
// Traditional way
Runnabler1 = newRunnable() {
@Override
publicvoidrun() {
inti = 0;
while (i++ < 10) {
System.out.println("It works");
}
}
};
// Lambda way
// If the lambda function has multiple lines use the {}
// Use the return statement if the lambda function need to return
// Following modifiers can be put on a lambda expression
// 1) Final keyword
// 2) Annotations
// It is not possible to specify the return type of a lambda expression
// We can omit the parameters types in lambda (String s1, String s2) can be written as (s1, s2)
Runnabler2 = () -> {
inti = 0;
while (i++ < 10) {
System.out.println("It works");
}
};
//call the runnable by calling r2.run();
}
}