我想按照下面的方式合并两个嵌套映射,而不覆盖外部映射值的数据,或者通过替换内部映射并覆盖已有的数据。
理想情况下,在嵌套映射中,我会保留已有的键/值对,并使用第二个映射添加到该键/值对中。
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"
)
)
我需要的结果如下:
val mapOne: MutableMap<String, MutableMap<String, String>> = mutableMapOf(
"DirectoryOne" to mutableMapOf(
"FeatureOne" to "SomeUniqueStringFeature1",
"FeatureTwo" to "SomeUniqueStringFeature2",
"FeatureThree" to "SomeUniqueStringFeature3"
)
)
只是为了详细阐述这背后的推理。我计划在运行时动态构建 map ,并向单个 map 添加功能,因为需要在应用程序的整个运行期间添加这些功能。
最佳答案
如果您想避免使用 Java 8 合并功能的尴尬,可以使用 getOrPut
。由于函数内联,这也更加高效。
此外,根据 Kotlin coding conventions ,最好使用常规的 for
循环而不是 forEach
(除非您在可空值上或在集合运算符链的末尾调用它)。
for ((key, map) in mapTwo) {
mapOne.getOrPut(key, ::mutableMapOf).putAll(map)
}
广义:
fun <K1, K2, V> MutableMap<in K1, MutableMap<K2, V>>.mergeIn(other: Map<out K1, Map<out K2, V>>) {
for ((key, map) in other) {
getOrPut(key, ::mutableMapOf).putAll(map)
}
}
关于kotlin - 合并具有相似外部键的嵌套映射,保留两个内部映射的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71185762/