Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a kotlin Map<String, String?> to Map<String, String> in a clear way?

Tags:

kotlin

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()
like image 471
zalpha314 Avatar asked Dec 02 '25 09:12

zalpha314


2 Answers

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()
like image 192
Alexey Romanov Avatar answered Dec 05 '25 08:12

Alexey Romanov


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) 
    }
like image 43
blackr4y Avatar answered Dec 05 '25 08:12

blackr4y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!