3

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()
3
  • 1
    I'd argue that there is nothing bad about !! in this particular situation: it's pretty simple function, and it's clear that there is no NPE. So I like your solution (it can be simplified/optimized by using kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/…) Commented Jul 23, 2019 at 20:38
  • if you've already filtered out all the null results then I don't see how your !! is unsafe Commented Jul 23, 2019 at 20:45
  • It's actually much more questionable that you have Map<..., ...?> in the first place. When I write your_map[k] and receive null, I would usually expect it to means that the key is not present in the map. Maybe it's possible to avoid creating such map at all? Commented Jul 23, 2019 at 20:59

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.