johnco3 johnco3 - 5 months ago 34
Java Question

Java Streams transform Map of EnumMap into a Map of lists

I wish to convert the following

enum Parameter {Foo, Bar, Baz};

Map<String, EnumMap<Parameter, String>> myMap = new HashMap(){{
put("KEY1", new EnumMap<>(Parameter.class) {{
put(Parameter.Foo, "BAD");
put(Parameter.Bar, "GOOD");
put(Parameter.Baz, "BAD");
}});
put("KEY2", new EnumMap<>(Parameter.class) {{
put(Parameter.Foo, "BAD");
put(Parameter.Bar, "GOOD");
put(Parameter.Baz, "GOOD");
}});
}};


into a filtered map where the filter will only contain either the

Map<String, List<Entry<Parameter, String>>> mapList


Where the resultant list should contain the rows with "GOOD" as the filter criteria.

I cannot figure out the correct stream syntax to do this, I know its along the following lines:

Map<String, List<Entry<Parameter, String>>> mapList =
myMap.entrySet().stream().groupingBy(e -> e.getKey()).collect(Collectors.toMap(????)

Answer

The entries are already grouped correctly, just the values need to be unwrapped and filtered:

import static java.util.stream.Collectors.*;
...
Map<String, List<Entry<Parameter, String>>> mapList = new HashMap<>();

myMap.forEach((k, v) -> { 
   Stream<Entry<Parameter, String>> filtered = v.entrySet().stream()
   .filter(e -> e.getValue().equals("GOOD"));

   if(reMapped.count() != 0) mapList.put(k, filtered.collect(toList()));
});