kotlin - 比较和组合 Hashmap 的键和值
kotlin - compare and combine key and values of Hashmap
我有 2 个 Hashmap
hashMap1 : HashMap<String, MutableList<String>> = {ab=["hello", "how", "are", "you"], cd=["my", "world"], ef = ["life", "is", "nice"]}
hashMap2 : HashMap<String, MutableList<String>> = {ab=["how", "you", "in", "life"], ef = ["nice", "to"], gd = ["fun"]}
我想比较 Hashmap 的键和值(字符串列表)并使用映射的值创建一个新映射
在上面的 2 个映射中,如果我比较键 -> ab 和 ef 匹配。 ab -> "how", "you" 和 ef -> "nice" 中的值匹配
因此我的新地图应该是
hashMap3 = {ab=["how", "you"], ef = ["nice"]}
如何获得此输出?
根据您描述的输入和输出猜测,我创建了适用于您的示例的测试用例:
@Test
fun `should return map with key-value pairs of only matching value strings`() {
val hashMap1 = hashMapOf(
"ab" to listOf("hello", "how", "are", "you"),
"cd" to listOf("my", "world"),
"ef" to listOf("life", "is", "nice")
)
val hashMap2 = hashMapOf(
"ab" to listOf("how", "you", "in", "life"),
"ef" to listOf("nice", "to"),
"gd" to listOf("fun")
)
val result = hashMap1
.filter { (key, _) -> hashMap2.containsKey(key) }
.mapValues { (key, value) -> hashMap2.getValue(key).filter { it in value } }
.filter { (_, value) -> value.isNotEmpty() }
assertThat(result).isEqualTo(
hashMapOf(
"ab" to listOf("how", "you"),
"ef" to listOf("nice")
)
)
}
我有 2 个 Hashmap
hashMap1 : HashMap<String, MutableList<String>> = {ab=["hello", "how", "are", "you"], cd=["my", "world"], ef = ["life", "is", "nice"]}
hashMap2 : HashMap<String, MutableList<String>> = {ab=["how", "you", "in", "life"], ef = ["nice", "to"], gd = ["fun"]}
我想比较 Hashmap 的键和值(字符串列表)并使用映射的值创建一个新映射
在上面的 2 个映射中,如果我比较键 -> ab 和 ef 匹配。 ab -> "how", "you" 和 ef -> "nice" 中的值匹配 因此我的新地图应该是
hashMap3 = {ab=["how", "you"], ef = ["nice"]}
如何获得此输出?
根据您描述的输入和输出猜测,我创建了适用于您的示例的测试用例:
@Test
fun `should return map with key-value pairs of only matching value strings`() {
val hashMap1 = hashMapOf(
"ab" to listOf("hello", "how", "are", "you"),
"cd" to listOf("my", "world"),
"ef" to listOf("life", "is", "nice")
)
val hashMap2 = hashMapOf(
"ab" to listOf("how", "you", "in", "life"),
"ef" to listOf("nice", "to"),
"gd" to listOf("fun")
)
val result = hashMap1
.filter { (key, _) -> hashMap2.containsKey(key) }
.mapValues { (key, value) -> hashMap2.getValue(key).filter { it in value } }
.filter { (_, value) -> value.isNotEmpty() }
assertThat(result).isEqualTo(
hashMapOf(
"ab" to listOf("how", "you"),
"ef" to listOf("nice")
)
)
}