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?
Do like this :
public class InverterMap {
public static void main(String[] args) {
Map<String, List<String>> mp = new HashMap<String, List<String>>();
mp.put("Fruit", Arrays.asList("Apple", "Orange"));
mp.put("Animal", Arrays.asList("Dog", "Cat"));
System.out.println(mp); // It returned {Fruit=[Apple, Orange], Animal=[Dog, Cat]}
Map<String, String> invertMap = mp.entrySet().stream().collect(HashMap::new,
(m, v) -> v.getValue().forEach(k -> m.put(k, v.getKey())), Map::putAll);
System.out.println(invertMap);// It returned {Apple=Fruit, Cat=Animal, Orange=Fruit, Dog=Animal}
}
}
Read Stream.collect(Supplier supplier, BiConsumer, BiConsumer combiner) for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With