johnco3 johnco3 - 1 year ago 108
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 Source

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

import static*;
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()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download