forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumMaps.java
More file actions
37 lines (35 loc) · 1.02 KB
/
EnumMaps.java
File metadata and controls
37 lines (35 loc) · 1.02 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
// enums/EnumMaps.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Basics of EnumMaps
// {java enums.EnumMaps}
package enums;
import java.util.*;
import static enums.AlarmPoints.*;
interface Command { void action(); }
public class EnumMaps {
public static void main(String[] args) {
EnumMap<AlarmPoints,Command> em =
new EnumMap<>(AlarmPoints.class);
em.put(KITCHEN,
() -> System.out.println("Kitchen fire!"));
em.put(BATHROOM,
() -> System.out.println("Bathroom alert!"));
for(Map.Entry<AlarmPoints,Command> e:
em.entrySet()) {
System.out.print(e.getKey() + ": ");
e.getValue().action();
}
try { // If there's no value for a particular key:
em.get(UTILITY).action();
} catch(Exception e) {
System.out.println("Expected: " + e);
}
}
}
/* Output:
BATHROOM: Bathroom alert!
KITCHEN: Kitchen fire!
Expected: java.lang.NullPointerException
*/