forked from WegraLee/effective-java-3e-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhase.java
More file actions
52 lines (45 loc) · 1.89 KB
/
Copy pathPhase.java
File metadata and controls
52 lines (45 loc) · 1.89 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
package effectivejava.chapter6.item37;
import java.util.*;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*;
// 코드 37-6 중첩 EnumMap으로 데이터와 열거 타입 쌍을 연결했다. (229-231쪽)
public enum Phase {
SOLID, LIQUID, GAS;
public enum Transition {
MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID),
BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID);
// // 코드 37-7 EnumMap 버전에 새로운 상태 추가하기 (231쪽)
// SOLID, LIQUID, GAS, PLASMA;
// public enum Transition {
// MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID),
// BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
// SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID),
// IONIZE(GAS, PLASMA), DEIONIZE(PLASMA, GAS);
private final Phase from;
private final Phase to;
Transition(Phase from, Phase to) {
this.from = from;
this.to = to;
}
// 상전이 맵을 초기화한다.
private static final Map<Phase, Map<Phase, Transition>>
m = Stream.of(values()).collect(groupingBy(t -> t.from,
() -> new EnumMap<>(Phase.class),
toMap(t -> t.to, t -> t,
(x, y) -> y, () -> new EnumMap<>(Phase.class))));
public static Transition from(Phase from, Phase to) {
return m.get(from).get(to);
}
}
// 간단한 데모 프로그램 - 깔끔하지 못한 표를 출력한다.
public static void main(String[] args) {
for (Phase src : Phase.values()) {
for (Phase dst : Phase.values()) {
Transition transition = Transition.from(src, dst);
if (transition != null)
System.out.printf("%s에서 %s로 : %s %n", src, dst, transition);
}
}
}
}