How to build a copy function map in Java’s lambda API
From the Java. Net that maps a pair of enums to values util. function. In bifunction, I want to build an enummap that reflects the mapping
For example, let E1 and E2 be enumeration types and t be 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);
Any pair of values of given E1 and E2 types
E1 e1 = //any valid value... E2 e2 = //any valid value....
The following two values should be equal:
T valueFromTheMaps = theMap.get(e1).get(e2); T valueFromTheFunction = theBiFunction.apply(e1,e2); boolean alwaysTrue = valueFromTheMaps.equals(valueFromTheFunction);
What is the best (more elegant, more efficient, etc.) implementation of the "magic" method?
Solution
If you use a generic solution and decompose it, you will get an elegant solution First, implement a generic function, which creates enummap from function, and then use the first function combined with itself to realize the nested mapping of bifunction:
static <T,E extends Enum<E>> EnumMap<E,T> funcToMap(Function<E,T> f,Class<E> t,E... values) { return Stream.of(values) .collect(Collectors.toMap(Function.identity(),f,(x,y)->x,()-> new EnumMap<>(t))); } static <T,E1 extends Enum<E1>,E2 extends Enum<E2>> EnumMap<E1,T>> biFuncToMap( BiFunction<E1,Class<E1> t1,Class<E2> t2,E1[] values1,E2[] values2){ return funcToMap(e1->funcToMap(e2->f.apply(e1,e2),t2,values2),t1,values1); }
This is a small test case:
enum Fruit { APPLE,PEAR } enum Color { RED,GREED,YELLOW }
…
EnumMap<Fruit,EnumMap<Color,String>> result =biFuncToMap((a,b)->b+" "+a,Fruit.class,Color.class,Fruit.values(),Color.values()); System.out.println(result);
→
{APPLE={RED=RED APPLE,GREED=GREED APPLE,YELLOW=YELLOW APPLE},PEAR={RED=RED PEAR,GREED=GREED PEAR,YELLOW=YELLOW PEAR}}
Of course, with a common solution, you can build methods for specific enumeration types that do not require class parameters
If the provided (BI) function is thread safe, it should work smoothly with parallel streams