
package me.whiteship.chapter06.item37.plant_ordinal;
import java.util.*;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;
// EnumMap을 사용해 열거 타입에 데이터를 연관시키기 (226-228쪽)
// 식물을 아주 단순하게 표현한 클래스 (226쪽)
class Plant {
enum LifeCycle { ANNUAL, PERENNIAL, BIENNIAL }
final String name;
final LifeCycle lifeCycle;
Plant(String name, LifeCycle lifeCycle) {
this.name = name;
this.lifeCycle = lifeCycle;
}
@Override public String toString() {
return name;
}
public static void main(String[] args) {
Plant[] garden = {
new Plant("바질", LifeCycle.ANNUAL),
new Plant("캐러웨이", LifeCycle.BIENNIAL),
new Plant("딜", LifeCycle.ANNUAL),
new Plant("라벤더", LifeCycle.PERENNIAL),
new Plant("파슬리", LifeCycle.BIENNIAL),
new Plant("로즈마리", LifeCycle.PERENNIAL)
};
// ANNUAL -> 바질, 딜
// PERENNIAL -> 라벤더, 로즈마리
// BiENNIAL -> 캐러웨이, 파슬리
// 코드 37-1 ordinal()을 배열 인덱스로 사용 - 따라 하지 말 것! (226쪽)
Set<Plant>[] plantsByLifeCycleArr =
(Set<Plant>[]) new Set[LifeCycle.values().length];
for (int i = 0; i < plantsByLifeCycleArr.length; i++)
plantsByLifeCycleArr[i] = new HashSet<>();
for (Plant p : garden)
plantsByLifeCycleArr[p.lifeCycle.ordinal()].add(p);
// 결과 출력
for (int i = 0; i < plantsByLifeCycleArr.length; i++) {
System.out.printf("%s: %s%n", LifeCycle.values()[i], plantsByLifeCycleArr[i]);
//ENUM에 이미 내용이 적혀져 있는데 해당 값을 잘 활용을 못하고 있다.
}
}
}

package me.whiteship.chapter06.item37.plant_enummap;
import java.util.*;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;
// EnumMap을 사용해 열거 타입에 데이터를 연관시키기 (226-228쪽)
// 식물을 아주 단순하게 표현한 클래스 (226쪽)
class Plant {
enum LifeCycle { ANNUAL, PERENNIAL, BIENNIAL }
final String name;
final LifeCycle lifeCycle;
Plant(String name, LifeCycle lifeCycle) {
this.name = name;
this.lifeCycle = lifeCycle;
}
@Override public String toString() {
return name;
}
public static void main(String[] args) {
Plant[] garden = {
new Plant("바질", LifeCycle.ANNUAL),
new Plant("캐러웨이", LifeCycle.BIENNIAL),
new Plant("딜", LifeCycle.ANNUAL),
new Plant("라벤더", LifeCycle.PERENNIAL),
new Plant("파슬리", LifeCycle.BIENNIAL),
new Plant("로즈마리", LifeCycle.PERENNIAL)
};
// 코드 37-2 EnumMap을 사용해 데이터와 열거 타입을 매핑한다. (227쪽)
Map<LifeCycle, Set<Plant>> plantsByLifeCycle =
new EnumMap<>(LifeCycle.class);
for (LifeCycle lc : LifeCycle.values())
plantsByLifeCycle.put(lc, new HashSet<>());
for (Plant p : garden)
plantsByLifeCycle.get(p.lifeCycle).add(p);
System.out.println(plantsByLifeCycle);
// 코드 37-3 스트림을 사용한 코드 1 - EnumMap을 사용하지 않는다! (228쪽)
Map<LifeCycle, List<Plant>> collect = Arrays.stream(garden)
.collect(groupingBy(p -> p.lifeCycle));
System.out.println(collect);
// 코드 37-4 스트림을 사용한 코드 2 - EnumMap을 이용해 데이터와 열거 타입을 매핑했다. (228쪽)
EnumMap<LifeCycle, Set<Plant>> collect1 = Arrays.stream(garden)
.collect(groupingBy(p -> p.lifeCycle,
() -> new EnumMap<>(LifeCycle.class), toSet()));
System.out.println(collect1);
}
}

stream을 사용하면 짧게 사용할 수 있다. stream을 사용하면 EnumMap을 사용하지 않는다. HashMap을 사용한다.
그렇게 하지 않으려면 맵을 만들어주고, Set으로 담는다.

없는 종류는 EnumMap을 만들어주지 않아서 더 효율적이다.
package me.whiteship.chapter06.item37.phase_ordinal;
import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
// 코드 37-6 중첩 EnumMap으로 데이터와 열거 타입 쌍을 연결했다. (229-231쪽)
public enum Phase {
SOLID, LIQUID, GAS;
public enum Transition {
MELT, FREEZE, BOIL, CONDENSE, SUBLIME, DEPOSIT;
private static final Transition[][] TRANSITIONS = {
{null, MELT, SUBLIME},
{FREEZE, null, BOIL},
{DEPOSIT, CONDENSE, null}
};
public static Transition from(Phase from, Phase to) {
return TRANSITIONS[from.ordinal()][to.ordinal()];
}
}
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);
}
}
}
}

ordinal을 사용해서 문제가 잇는 것이다.
package me.whiteship.chapter06.item37.phase_enummap;
import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
// 코드 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 = new EnumMap<>(Phase.class);
// static {
// for (Transition t : Transition.values()) {
// m.computeIfAbsent(t.from, k -> new EnumMap<>(Phase.class)).put(t.to, t);
// }
// }
// static {
// for (Transition t : Transition.values()) {
// Map<Phase, Transition> innerMap = m.get(t.from);
// if (innerMap == null) {
// innerMap = new EnumMap<>(Phase.class);
// m.put(t.from, innerMap);
// }
// innerMap.put(t.to, t);
// }
// }
// @formatter:off
// 상전이 맵을 초기화한다.
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)))
);
// @formatter:on
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);
}
}
}
}
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)))
);
from => to 일 때 Transition을 사용한다는 것이다.
static {
for (Transition t : Transition.values()) {
Map<Phase, Transition> innerMap = m.get(t.from);
if (innerMap == null) {
innerMap = new EnumMap<>(Phase.class);
m.put(t.from, innerMap);
}
innerMap.put(t.to, t);
}
}
private static final Map<Phase, Map<Phase, Transition>> m = new EnumMap<>(Phase.class);
static {
for (Transition t : Transition.values()) {
m.computeIfAbsent(t.from, k -> new EnumMap<>(Phase.class)).put(t.to, t);
}
}
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)))
);
위 3개는 다 동일한 코드이다. 위에서부터 밑으로 줄일만큼 줄인 코드이다.

package me.whiteship.chapter06.item37.enummap;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
public class EnumMapExample {
enum LifeCycle {
ANNUAL, PERENNIAL, BIENNIAL
}
public static void main(String[] args) {
Map<LifeCycle, String> plantsByLifeCycle = new EnumMap<>(LifeCycle.class);
plantsByLifeCycle.put(LifeCycle.PERENNIAL, "라벤더");
plantsByLifeCycle.put(LifeCycle.ANNUAL, "바질");
plantsByLifeCycle.put(LifeCycle.BIENNIAL, "파슬리");
System.out.println(plantsByLifeCycle);
Map<LifeCycle, String> plantsByLifeCycle2 = Collections.synchronizedMap(new EnumMap<>(LifeCycle.class));
plantsByLifeCycle2.put(LifeCycle.PERENNIAL, "라벤더");
}
}
타입을 필요로 하기 때문에 해당 타입을 같이 줘야 한다.
동기화가 되어있지 않다.
ordinal로 사용하지 말자.
Collections.synchronizedMap로 감싸면 멀티스레드에 안전하다.