Creation multimap throught lambda-expression

42 views Asked by At

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:

  1. Expression Stream.of(values()) creates and returns an array of enum Transition elements
  2. Expression t -> t.from merely means that each element of enum Transition array, returning by command Stream.of(values()) maps to Phase from element.
  3. Expression () -> new EnumMap<>(Phase.class) probably means that there is to be created map for each Phase from element.
  4. Here I am at stupor.
0

There are 0 answers