forked from Apress/functional-interfaces-in-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayfulPets.java
More file actions
76 lines (67 loc) · 2.27 KB
/
PlayfulPets.java
File metadata and controls
76 lines (67 loc) · 2.27 KB
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
package chapter1;
import java.util.*;
@FunctionalInterface
interface PetMatcher
{
List<Pet> match(Pet pet);
default Pet first(Pet pet)
{
int index = Pet.pets.indexOf(pet);
return index > -1? Pet.pets.get(index) : null;
}
}
public class PlayfulPets
{
private static void matchPet(String criteria,
PetMatcher matcher, Pet pet)
{
System.out.println("\n" + criteria + ":");
System.out.println("First: " + matcher.first(pet));
System.out.println("All matches:");
List<Pet> matches = matcher.match(pet);
for (Pet p : matches)
System.out.println(p);
}
public static void main(String[] args)
{
Pet.pets.add(new Pet("Scruffy","dog","poodle",
"white",895.00));
Pet.pets.add(new Pet("Meow","cat","siamese","white",740.25));
Pet.pets.add(new Pet("Max","dog","poodle","black",540.50));
Pet.pets.add(new Pet("Cuddles","dog","pug","black",1282.75));
Pet.pets.add(new Pet("Slider","snake","garden",
"green",320.00));
PetMatcher breedMatcher = new PetMatcher() {
public List<Pet> match(Pet pet)
{
List<Pet> matches = new ArrayList<>();
for (Pet p : Pet.pets)
if (p.equals(pet))
matches.add(p);
return matches;
}
};
PetMatcher priceMatcher = new PetMatcher() {
public List<Pet> match(Pet pet)
{
List<Pet> matches = new ArrayList<>();
for (Pet p : Pet.pets)
if (p.price <= pet.price)
matches.add(p);
return matches;
}
public Pet first(Pet pet)
{
int index = -1;
for(Pet p : Pet.pets)
if (p.price <= pet.price)
return p;
return null;
}
};
matchPet("Poodles",breedMatcher,
new Pet(null, "dog", "poodle", null, 0.0));
matchPet("Pets for $800 or less",priceMatcher,
new Pet(null, null, null, null, 800.0));
}
}