is there a built-in method that lets me filter a `...
# announcements
f
is there a built-in method that lets me filter a
Map<K,V?>
to
Map<K,V>
? I.e. filter all null values and cast the map?
r
what is the difference?
one can have null values?
f
Yes, the input can have null values for V, the second map not
v
What would be the benefit? Retrieving a value from a map is always nullable, as the key might be absent.
To just filter out
null
values you can do
.filterValues { it != null }
Otherwise the best I can up with is
.filterValues { it != null }.mapValues { it.value as V }
Or as extension function
Copy code
fun <K, V> Map<K, V?>.filterValuesNotNull() =
        filterValues { it != null }.mapValues { it.value as V }
t
There isn't a built in function for this, but you can create one like shown by @Vampire For those wondering: it can make a difference, depending on how you use it. • a check for
myKey in myMap
can return true, but
myMap[myKey]
would still return null • when using
entries
,
forEach
or something alike, you can get entries with
null
values • Basically everything except for the simple
get
call behaves differently
☝️ 1
f
exactly that was my intention. the additional
mapValues
variant looks mjuch nicer than the cast I did, will try that, thanks!