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()
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()
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With