我想过滤掉所有具有空值的对
val mapOfNotEmptyPairs: Map<String, String> = mapOf("key" to Some("value"), "secondKey" to None)
预期:
print(mapOfNotEmptyPairs)
// {key=value}
最佳答案
原版 Kotlin
val rawMap = mapOf<String, String?>(
"key" to "value", "secondKey" to null)
// Note that this doesn't adjust the type. If needed, use
// a cast (as Map<String,String>) or mapValues{ it.value!! }
val filteredMap = rawMap.filterValues { it != null }
System.out.println(filteredMap)
p.s 使用箭头选项时
val rawMap = mapOf<String, Option<String>>(
mapOf("key" to Some("value"), "secondKey" to None)
val transformedMap = rawMap
.filterValues { it.isDefined() }
.mapValues { it.value.orNull()!! }
p.p.s 当使用 Arrow Option 及其 filterMap 扩展函数时;
val rawMap = mapOf<String, Option<String>>(
mapOf("key" to Some("value"), "secondKey" to None)
val transformedMap = rawMap
.filterMap { it.value.orNull() }
关于kotlin - 从 map 中剪切具有空值的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66912721/