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
.
A solution that doesn't need constructing temporary Map.Entry
instances, is:
Map<String, String> result = source.entrySet().stream()
.collect(HashMap::new, (m,e)->e.getValue().forEach(k->m.put(k,e.getKey())), Map::putAll);
You might notice the similarity to the non-stream solution
Map<String, String> result = new HashMap<>();
source.forEach((key, value) -> value.forEach(k -> result.put(k, key)));
or the pre-Java 8 solution
Map<String, String> result = new HashMap<>();
for(Map.Entry<String,List<String>> e: source.entrySet())
for(String key: e.getValue()) result.put(key, e.getKey());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.