kotlin-比较并组合Hashmap的键和值
我有两个Hashmapkotlin-比较并组合Hashmap的键和值,kotlin,hashmap,Kotlin,Hashmap,我有两个Hashmap hashMap1 : HashMap<String, MutableList<String>> = {ab=["hello", "how", "are", "you"], cd=["my", "world"], ef = ["life", "is", "nice"]} h
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"]}
如何获得此输出?根据您描述的输入和输出猜测,我创建了此测试用例,适用于您的示例:
@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")
)
)
}
让我们知道您尝试了什么请为您的示例添加有效的kotlin代码谢谢您的帮助。
@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")
)
)
}