Reputation: 1495
I'd like to find the clearest and most elegant way to convert a Map<String, String?>
to a Map<String, String>
, filtering out the pairs with null
values.
I have a contrived solution below, but I don't like how I have to do an unsafe !!
. Is there a better way to do this?
fun Map<String, String?>.filterNonNull() = this
.filter { it.value != null }
.map { it.key to it.value!! }
.toMap()
Upvotes: 3
Views: 1203
Reputation: 279
Based on the discussion here you can also use something like this:
fun <K, V> Map<K, V?>.filterNotNullValues(): Map<K, V> =
mutableMapOf<K, V>().apply {
for ((k, v) in this@filterNotNullValues) if (v != null) put(k, v)
}
Upvotes: 2
Reputation: 170899
mapNotNull
serves as a combination of map
and filter
, but returns a List
and not the Map
you want so
fun <K, V> Map<K, V?>.filterNonNull(): Map<K, V> =
this.mapNotNull {
(key, value) -> if (value == null) null else Pair(key, value)
}.toMap()
Upvotes: 2