I have 2 maps defined as Map<String, Set<String>>
:
map1 : {
Honda=[Accord, Civic, CRV],
Toyota=[Corola, RAV4, Yaris]
}
map2 : {
Accord=[5w30, 10w40],
Civic=[0w30, 5w30, 5w40],
CRV=[5w30, 5w40, 10w40],
Corola=[0w30, 10w40],
RAV4=[0w20, 0w30, 5w30]
}
I need merge this 2 maps so the result map key will be brand name (e.g. Honda, Toyota) and values will be all of oils. Some like this:
mergeMap: {
Honda=[0w30, 5w30, 5w40, 10w40],
Toyota=[0w20, 0w30, 5w30, 10w40]
}
I wrote sam old school method which use forEach
blocks, but I think that it can be better using streams and so on. Is it possible? If yes, how?
CodePudding user response:
Since the resulting map will have the same keys, you can use mapValues
.
In the lambda, flatMap
each of the strings in the values set to the corresponding value in the second map, if it exists.
map1.mapValues { (_, v) -> v.flatMap { map2[it] ?: emptyList() }.toSortedSet() }
This gives you a Map<String, SortedSet<String>>
.
Note that this will sort the “0w30” strings lexicographically, as they are strings, so you won’t get the exact order you want. I don’t know what these strings represent, but you should probably represent them with a data class implementing Comparable
instead. That’d give you the correct order.