|
| 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