I have a list of keys `keys` and another map of ke...
# announcements
w
I have a list of keys
keys
and another map of key -> value
map
, whose keys are a subset of
keys
and whose value is either
SOFT_DELETED
or
NOT_DELETED
. For example:
Copy code
val keys = listOf("key1", "key2", "key3")
val map = mapOf("key1" to "SOFT_DELETED", "key2" to "NOT_DELETED")
I need to combine
keys
and
map
to generate another map
finalMap
, whose keys will contain all keys from
keys
that are not in keys of
map
with values of
DELETED
and keys of
map
that has a value of
SOFT_DELETED
. In the above example, I’d have:
Copy code
val finalMap = mapOf("key1" to "SOFT_DELETED", "key3" to "DELETED")
I can think of mapping over
keys
and check each key against
map
and generate
finalMap
, like:
Copy code
val finalMap = keys.mapNotNull {
  when(map[it]) {
    "SOFT_DELETED") -> it to "SOFT_DELETED"
    null -> it to "DELETED"
    else -> null
  }
}
Is there a more idiomatic way in kotlin to do this?
e
Copy code
val finalMap = keys.filter { map[it] != "NOT_DELETED" }
.mapNotNull { it to map[it] ?: "DELETED" }
w
This looks better than what I had.