I have a map like bellow,
[key = "car", value = ["bmw", "toyota"]]
[key = "bike", value = ["honda", "kawasaki"]]
I want to convert it to another map using java 8 functional apis like bellow,
[key = "bmw", value = "car"]
[key = "toyota", value = "car"]
[key = "honda", value = "bike"]
[key = "kawasaki", value = "bike"]
Flatten the map values to entries then collect them:
Map<String, String> m2 = map
.entrySet()
.stream()
.flatMap(e -> e.getValue().stream().map(v -> new AbstractMap.SimpleEntry<>(v, e.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
This can be shortened by importing AbstractMap.SimpleEntry and Map.Entry.
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