2

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

val mapOfNotEmptyPairs: Map<String, String> = mapOf("key" to Some("value"), "secondKey" to None)

预期的:

print(mapOfNotEmptyPairs)
// {key=value}
4

2 回答 2

2

香草科特林

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)

ps 使用箭头选项时

val rawMap = mapOf<String, Option<String>>(
    mapOf("key" to Some("value"), "secondKey" to None)

val transformedMap = rawMap
   .filterValues { it.isDefined() }
   .mapValues { it.value.orNull()!! } 

pps 使用 Arrow Option 及其 filterMap 扩展功能时;

val rawMap = mapOf<String, Option<String>>(
    mapOf("key" to Some("value"), "secondKey" to None)

val transformedMap = rawMap
   .filterMap { it.value.orNull() } 

于 2021-04-01T23:56:01.410 回答
1
val mapOfNotEmptyPairs =
        mapOf("key" to Some("value"), "secondKey" to None)
            .filterValues { it is Some<String> } // or { it !is None } or { it.isDefined() }
            .mapValues { (_, v) -> (v as Some<String>).t }
于 2021-04-02T22:50:37.807 回答