kotlin - 从 map 中剪切具有空值的对

标签 kotlin arrow-kt

我想过滤掉所有具有空值的对

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/

相关文章:

kotlin - 如何覆盖哈希码

scala - JVM 语言中如何编译嵌套函数和词法作用域?

kotlin - 定期发出最后一个值以及新值到达时的流

spring-boot - 当我点击 “Execute”按钮时更改Swagger UI请求URL

Kotlin 箭头组合经过验证的列表

monads - 为什么验证会违反 monad 法则?

kotlin - 如何类型安全将 Either 的集合减少到仅 Right

gradle - 无法为@higherkind 和@extension 生成对象

kotlin - 使用协程在 kotlin 中的列表上实现 monad 理解

nullable - 在 Kotlin 中,处理可为空值、引用或转换它们的惯用方法是什么?