I have a map read from my static config in the following format:
Map<String, Map<String, List<String>>> dependentPluginEntityMapString.
The string values in this map are actually from ENUMs and the correct and required representation of the map is Map<ENUM_A, Map<ENUM_A, List<ENUM_B>>>.
ENUM_A {
APPLE, BANANA
}
ENUM_B {
ONION, RADDISH
}
- How can I convert the map of strings to the one with enums
Map<ENUM_A, Map<ENUM_A, List<ENUM_B>>>for more type safety?
I know, I can iterate on the string map (using for or streams) and create a new map with enums as required but looking for a better/more efficient and an elegant way of doing that?
This is my brute solution. Can i do better?
final Map<ENUM_A, Map<ENUM_A, List<ENUM_B>>> dependentPluginEntityMap = new HashMap<>();
for (Map.Entry<String, Map<String, List<String>>> dependentPluginEntry:
dependentPluginEntityMapFromAppConfig.entrySet()) {
final Map<ENUM_A, List<ENUM_B>> independentPluginMapForEntry = new HashMap<>();
if (MapUtils.isNotEmpty(dependentPluginEntry.getValue())) {
for (Map.Entry<String, List<String>> independentPluginEntry:
dependentPluginEntry.getValue().entrySet()) {
if (CollectionUtils.isNotEmpty(independentPluginEntry.getValue())) {
independentPluginMapForEntry.put(ENUM_A.valueOf(independentPluginEntry.getKey()),
independentPluginEntry.getValue().stream().map(value -> ENUM_B.valueOf(value))
.collect(Collectors.toList()));
}
}
}
dependentPluginEntityMap.put(ENUM_A.valueOf(dependentPluginEntry.getKey()),
independentPluginMapForEntry);
}
- Should I convert the map of strings to ENUMMAP , instead of map with enum keys? Will it work with my nested map structure?
Any leads apprecciated.
EnumMaprequires that the constants that serve as keys in the map all be members of the same enum class. It is not possible to create anEnumMapwith a non-concrete type token, unfortunately. A workaround for your use case would be to make the enum types implement a common interface, and then to use the interface type as the map keys. You will not be able to use theEnumMapclass in this solution,, though.