0

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.

Nizbel99
  • 123
  • 6

2 Answers2

1
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);
jaco0646
  • 15,303
  • 7
  • 59
  • 83
0

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()])));
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • I thought it was considered bad practice to use .ordinal() since we can't make guarantees on order? Though that is the type of mapping I am after. – Nizbel99 Oct 08 '20 at 19:01
  • _I thought it was considered bad practice to use_ Depends if enum values may change in the future then it's less maintainable. A way can be use value with the enum constants like `enum First { A(1), B(2),C(3)...` [Read here](https://stackoverflow.com/questions/44654291/is-it-good-practice-to-use-ordinal-of-enum) _we can't make guarantees on order_ That's not true if you not change the order in the enum defination, order will be always same. – Eklavya Oct 08 '20 at 19:17
  • Did you get your answer ? – Eklavya Oct 23 '20 at 17:12