I would like to remove elements from a collection,...
# getting-started
d
I would like to remove elements from a collection, based on a condition. For a list, we can use:
Copy code
myList.removeAll { it.myField != myFieldValue }
But for a map, there doesn’t seem to be
removeAll
:
Copy code
myMap.removeAll { it.key != myKeyValue }    <--- removeAll doesn't exist
what should I use instead?
l
Maybe
myMap.filter { it.key == myKeyValue }
?
It creates a new map though
d
my map is defined as:
Copy code
val myMap : MutableMap<Int, MyObject>
so, being a val, a new map cannot be set
i
myMap.keys.removeAll { it != myKeyValue }
d
@ilya.gorbunov thanks! it works
e
there is a logically negated function as well:
Copy code
myMap.keys.retainAll { it == myKeyValue }
👍 1
but if you want to remove everything in the map except for a single entry, consider something like
Copy code
val value = myMap[myKeyValue]
myMap.clear()
if (value != null) myMap[myKeyValue] = value
which doesn't require an external iteration
👍 1