Cut pairs with empty values from map

Viewed 124

I'd like to filter out all the pairs with empty values

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

expected:

print(mapOfNotEmptyPairs)
// {key=value}
2 Answers

Vanilla 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 When using Arrow Option

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 When using Arrow Option and their filterMap extension function;

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

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

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 }
Related