Java Initialize EnumBiMap From Two Enum Types

168 Views Asked by At

What's the most convenient way to initialize an EnumBiMap from two different enum types? I have the following scenario:

public enum First {
  A,
  B,
  C
}

and

public enum Second {
  ALPHA,
  BETA,
  GAMMA
}

I have tried something like

        private static EnumBiMap<First, Second> typeMap =
            EnumBiMap<First, Second>.create(
                   Arrays.stream(First.values()).collect(Collectors.toMap(
                            Function.identity(), type -> {
                                switch(type) {
                                    case First.A:
                                        return Second.ALPHA;
                                    case First.B:
                                        return Second.BETA;
                                    default:
                                        return Second.GAMMA
                                }})));

But I lose the type information so I get errors. Is there a nicer way to get this mapping? I also can't daisy-chain puts since put() just returns the value as opposed to a reference to the map. In my case, the map could also be immutable.

2

There are 2 best solutions below

0
On
import com.google.common.collect.EnumBiMap;
import com.google.common.collect.Streams;
import static java.util.Arrays.stream;

EnumBiMap<First, Second> map = EnumBiMap.create(First.class, Second.class);
Streams.forEachPair(stream(First.values()), stream(Second.values()), map::put);
3
On

The way you are mapping seems like mapping ordinally. Then you can use the ordinal value using .ordinal() of the enum to create the map.

EnumBiMap<First, Second>.create(
      Arrays.stream(First.values())
             .collect(Collectors.toMap(Function.identity(),
                                       e -> Second.values()[e.ordinal()])));