-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLambdaExample.java
80 lines (61 loc) · 2.09 KB
/
LambdaExample.java
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
71
72
73
74
75
76
77
78
79
80
package java8;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class LambdaExample {
public static void main(final String[] args) {
final UsersRepository repository = new UsersRepository();
banner("Listing all users");
repository.select(null, null);
banner("Listing users with age > 5 sorted by name");
// TODO once using anonymous objects and once using lambda expressions
banner("Listing users with age < 10 sorted by age");
// TODO once using anonymous objects and once using lambda expressions
banner("Listing active users sorted by name");
// TODO once using anonymous objects and once using lambda expressions
banner("Listing active users with age > 8 sorted by name");
// TODO once using anonymous objects and once using lambda expressions
}
private static void banner(final String m) {
System.out.println("#### " + m + " ####");
}
}
class UsersRepository {
List<User> users;
UsersRepository() {
users = Arrays.asList(
new User("Seven", 7, true),
new User("Four", 4, false),
new User("Eleven", 11, true),
new User("Three", 3, true),
new User("Nine", 9, false),
new User("One", 1, true),
new User("Twelve", 12, true));
}
void select(final Predicate<User> filter, final Comparator<User> order) {
Stream<User> usersStream = users.stream();
if (filter != null) {
usersStream = usersStream.filter(filter);
}
if (order != null) {
usersStream = usersStream.sorted(order);
}
usersStream.forEach(System.out::println);
}
}
class User {
String name;
int age;
boolean active;
User(final String name, final int age, boolean active) {
this.name = name;
this.age = age;
this.active = active;
}
@Override
public String toString() {
return name + "\t| " + age;
}
}