Search code examples
javacollectionsjava-8java-stream

Invert Map <String, List<String>> using Java 8 streams


I need to invert a map which is <String, List<String>> to Map<String,String> using Java 8, with the assumption that the values are unique. For example,

Input map -

{"Fruit" -> ["apple","orange"], "Animal" -> ["Dog","Cat"]}

Output map

{"apple" -> "Fruit", "orange" -> "Fruit", "Dog"->"Animal", "Cat" -> "Animal"}
Map <String, String> outputMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : inputMap.entrySet()) {
    entry.getValue().forEach(value -> outputMap.put(value, entry.getKey()));
}   

Is this right? Can we achieve this using streams Java 8?


Solution

  • You an try this way

    Map <String, String> updatedMap = new HashMap<>();
    oldMap.keySet()
          .forEach(i -> oldMap.get(i)
                              .forEach(k -> updatedMap.put(k, i)));