I am reading a book "Effective Java" and coming up with fragmnet of code:
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);
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);
}
}
}
But I can't understand lambda expression details helping to create such a multimap: I mean what does command toMap(t -> t.to, t -> t, (x, y) -> y, () -> new EnumMap<>(Phase.class))))); make? Perhaphs, I am silly, but this is really difficult to me.
What I do understand:
- Expression
Stream.of(values())creates and returns an array ofenum Transitionelements - Expression
t -> t.frommerely means that each element ofenum Transitionarray, returning by commandStream.of(values())maps toPhase fromelement. - Expression
() -> new EnumMap<>(Phase.class)probably means that there is to be created map for eachPhase fromelement. - Here I am at stupor.