From a java.util.function.BiFunction that maps a pair of Enums into a value, I want to build a EnumMap that reflects that mapping.
For instance, let E1 and E2 be enum types and T any given type:
BiFunction<E1,E2, T> theBiFunction = //...anything
EnumMap<E1,EnumMap<E2,T>> theMap =
buildTheMap( // <-- this is where the magic happens
E1.values(),
E2.values(),
theBiFunction);
Given any pair of values of type E1 and E2
E1 e1 = //any valid value...
E2 e2 = //any valid value....
both values below should be equal:
T valueFromTheMaps = theMap.get(e1).get(e2);
T valueFromTheFunction = theBiFunction.apply(e1,e2);
boolean alwaysTrue = valueFromTheMaps.equals(valueFromTheFunction);
What's the best (more elegant, efficient, etc...) implementation for the method where the "magic" takes place?
You get an elegant solution if you go to a generic solution and break it down. First, implement a generic function which creates an
EnumMapout of aFunction, then implement the nested mapping of aBiFunctionusing the first function combined with itself:Here’s a little test case:
…
→
Of course, using the generic solution you can built methods for concrete
enumtypes which do not require theClassparameter(s)…This ought to work smoothly with a parallel stream if the provided
(Bi)Functionis thread safe.