Skip to content

Commit 9178d4a

Browse files
authored
Create tutorial_53.java
1 parent cc2776f commit 9178d4a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

code/tutorial_53.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
@FunctionalInterface
2+
interface Filter {
3+
boolean test(String n);
4+
}
5+
@FunctionalInterface
6+
interface Adder {
7+
int run(int n1, int n2);
8+
}
9+
//
10+
//
11+
public class Driver {
12+
13+
public static void main(String[] args) {
14+
15+
// main example
16+
String[] friends = { "jim", "kate", "bill", "mark", "devin", "alice", "melvin", "jeremy", "bob" };
17+
18+
Messenger group = new Messenger(friends);
19+
String mess = "RSVP to my party.";
20+
21+
group.send(mess, n -> n.charAt(0) == 'm');
22+
group.send(mess, n -> n.length() == 4);
23+
group.send(mess, n -> true);
24+
25+
// create a lambda
26+
Adder add = (a, b) -> a + b;
27+
28+
// execute a lambda
29+
int result1 = add.run(56, 79);
30+
31+
// execute a lambda immediately
32+
int result2 = ( (Adder) (a, b) -> a + b ).run(13,28);
33+
34+
// multiple statements in a lambda
35+
int result3 = ((Adder)(a, b) -> {
36+
System.out.print("The result = ");
37+
return a + b;
38+
}).run(5, 16);
39+
System.out.println(result3);
40+
}
41+
42+
}
43+
//
44+
//
45+
class Messenger {
46+
47+
protected String[] contactList;
48+
49+
public Messenger(String[] names) {
50+
contactList = names;
51+
}
52+
53+
public void send(String message, Filter filter) {
54+
for (String name: contactList) {
55+
if (filter.test(name)) {
56+
System.out.println(name + ": " + message);
57+
}
58+
}
59+
}
60+
61+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy