简体   繁体   English

将两张地图合二为一

[英]Merge two maps into one

I have to maps.我必须映射。 One is Map<String, Double> , like "USA, 55.87".一种是Map<String, Double> ,例如“USA, 55.87”。 Second is Map<String, String> , like "USA, United States of America".其次是Map<String, String> ,如“USA, United States of America”。

And I want to turn this maps into Map<Result, Double> .我想把这张地图变成Map<Result, Double> Where Result contains two String, like "USA, United States of America".其中Result包含两个字符串,例如“USA, United States of America”。 How to do that?怎么做?

data class Result(
  val abbreviation: String,
  val name: String
)

fun main() {
  val firstMap = mapOf("USA" to 12.34, "CAN" to 56.78, "MEX" to 90.12)
  val secondMap = mapOf("USA" to "United States of America", "MEX" to "Mexico", "GON" to "Gondor")

  val result = firstMap.keys.intersect(secondMap.keys).associate { Result(it, secondMap[it]!!) to firstMap[it] }

  println(result)
}

firstMap.keys.intersect(secondMap.keys) will give you the set of keys in common between your two maps, in case there are keys that are only in one map and not the other. firstMap.keys.intersect(secondMap.keys)将为您提供两个地图之间共有的一组键,以防只有一个 map 而不是另一个。 associate() builds a Map , where you are passed a collection member (in this case, a map key) and you return a Pair representing an entry in the resulting Map . associate()构建一个Map ,其中向您传递了一个集合成员(在本例中为 map 键),并且您返回一个Pair代表生成的Map中的条目。

If you have strong reason to believe that the keys in both maps will always match, you can do the following:如果您有充分的理由相信两个映射中的键将始终匹配,您可以执行以下操作:

data class Country(
    val abbreviation: String,
    val name: String
)

fun main() {
    val firstMap = mapOf("USA" to 12.34)
    val secondMap = mapOf("USA" to "United States of America")

    print(firstMap.mapKeys { Country(it.key, secondMap[it.key] ?: error("Country ${it.key} not found in second map")) })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM