-
Notifications
You must be signed in to change notification settings - Fork 11
/
ImplementingFunctionalInterfacesWithLambdas.java
83 lines (73 loc) · 2 KB
/
ImplementingFunctionalInterfacesWithLambdas.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
81
82
83
package designPatternsAndPrinciples;
import java.util.List;
import java.util.function.Predicate;
/**
*
* @author chengfeili
* Jun 4, 2017 10:18:55 PM
*
*
* ---------Valid lambda syntax:------------------
* () -> new Duck()
* d -> {return d.quack();}
* (Duck d) -> d.quack()
* (Animal a, Duck d) -> d.quack()
*
* () - true
* a -> {return a.startsWith("a");}
* (String a) -> a.startsWith("a)
* (int x) -> {}
* (int y) -> {return;}
* (a, b) -> a.startsWith("a)
*
*
* -----------Invalid lambda syntax: ---------------
* Duck d -> d.quack() ==> (Duck d) -> d.quack()
* a,d -> d.quack() ==> (a, d) -> d.quack()
* Animal a, Duck d -> d.quack() ==> (Animal a, Duck d) -> d.quack()
*
* a, b -> a.startsWith("a") ==> (a, b) -> a.startsWith("a")
*
* (when one parameter has a data type listed, though,
* all parameters must provide a data type)
* (int y, z) -> {int x = 1; return y + 10;}
*
* (a, b) -> {int a = 0; return 5;} (a is redeclared)
*/
class Animal {
private String species;
private boolean canHop;
private boolean canSwim;
public Animal(String species, boolean canHop, boolean canSwim) {
this.species = species;
this.canHop = canHop;
this.canSwim = canSwim;
}
public Animal(String species2, int age, List<String> favoriteFoods) {
}
public boolean canHop() {
return canHop;
}
public boolean canSwim() {
return canSwim;
}
public String toString() {
return species;
}
}
@FunctionalInterface
interface CheckTrait {
public boolean test(Animal a);
}
public class ImplementingFunctionalInterfacesWithLambdas {
private static void print(Animal animal, Predicate<Animal> trait) {
if (trait.test(animal))
System.out.println(animal);
}
public static void main(String[] args) {
// Java relies on context when figuring out what lambda expressions mean
// a -> a.canHop() ==> (Animal a) -> {return a.canHop();}
print(new Animal("fish", false, true), a -> a.canHop());
print(new Animal("kangaroo", true, false), a -> a.canHop());
}
}