-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtutorial_53.java
61 lines (48 loc) · 1.38 KB
/
tutorial_53.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
@FunctionalInterface
interface Filter {
boolean test(String n);
}
@FunctionalInterface
interface Adder {
int run(int n1, int n2);
}
//
//
public class Driver {
public static void main(String[] args) {
// main example
String[] friends = { "jim", "kate", "bill", "mark", "devin", "alice", "melvin", "jeremy", "bob" };
Messenger group = new Messenger(friends);
String mess = "RSVP to my party.";
group.send(mess, n -> n.charAt(0) == 'm');
group.send(mess, n -> n.length() == 4);
group.send(mess, n -> true);
// create a lambda
Adder add = (a, b) -> a + b;
// execute a lambda
int result1 = add.run(56, 79);
// execute a lambda immediately
int result2 = ( (Adder) (a, b) -> a + b ).run(13,28);
// multiple statements in a lambda
int result3 = ((Adder)(a, b) -> {
System.out.print("The result = ");
return a + b;
}).run(5, 16);
System.out.println(result3);
}
}
//
//
class Messenger {
protected String[] contactList;
public Messenger(String[] names) {
contactList = names;
}
public void send(String message, Filter filter) {
for (String name: contactList) {
if (filter.test(name)) {
System.out.println(name + ": " + message);
}
}
}
}