Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a Map<String, List<String>> to Map<String, String> in java 8 functional APIs

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"]
like image 556
faisalbegins Avatar asked Oct 28 '25 03:10

faisalbegins


1 Answers

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.

like image 71
teppic Avatar answered Oct 29 '25 18:10

teppic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!