'Merge nested maps with similar outer keys, keeping both inner map's key value pairs
I would like to merge two nested maps as per below, without overwriting the data of the outer map's values, or by replacing the inner map, and overwriting the data already there.
Ideally within the nested map, I would keep the key/value pairs I already have, and add to that with the second map.
val mapOne: MutableMap<String, MutableMap<String, String>> = mutableMapOf(
"DirectoryOne" to mutableMapOf(
"FeatureOne" to "SomeUniqueStringFeature1",
"FeatureTwo" to "SomeUniqueStringFeature2"
)
)
val mapTwo: MutableMap<String, MutableMap<String, String>> = mutableMapOf(
"DirectoryOne" to mutableMapOf(
"FeatureThree" to "SomeUniqueStringFeature3"
)
)
The result I need would look as follows:
val mapOne: MutableMap<String, MutableMap<String, String>> = mutableMapOf(
"DirectoryOne" to mutableMapOf(
"FeatureOne" to "SomeUniqueStringFeature1",
"FeatureTwo" to "SomeUniqueStringFeature2",
"FeatureThree" to "SomeUniqueStringFeature3"
)
)
Just to elaborate some into reasoning behind this. I am planning on building the map dynamically at runtime and add features to a single map as they are required to be added throughout the duration of the application.
Solution 1:[1]
I was able to perform the desired action with the below code. Iterating over the outer key/value pairs and merging the nested key/value pairs with a BiConsumer/BiFunction to mapOne. (Typing got a bit burdensome)
mapTwo.forEach(BiConsumer { k: String, v: MutableMap<String, String> ->
mapOne.merge(k, v,
BiFunction { v1: MutableMap<String, String>, v2: MutableMap<String, String> ->
v1.putAll(v2)
v1
})
})
I soon discovered that I could more easily employ a lambda (Removing the BiConsumer/BiFunction) and then move the lambda out of the merge parenthesis. The final optimal solution is shown below.
mapTwo.forEach { (k: String, v: MutableMap<String, String>) ->
mapOne.merge(k, v
) { v1: MutableMap<String, String>, v2: MutableMap<String, String> ->
v1.putAll(v2)
v1
}
}
I am wrapping the above snippet in a function/method to be able to apply this multiple times where needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kevin Smith |
