https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

06/02/2021, 2:05 PM
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

Luke

06/02/2021, 2:16 PM
Maybe
myMap.filter { it.key == myKeyValue }
?
It creates a new map though
d

Daniele B

06/02/2021, 2:19 PM
my map is defined as:
Copy code
val myMap : MutableMap<Int, MyObject>
so, being a val, a new map cannot be set
i

ilya.gorbunov

06/02/2021, 2:20 PM
myMap.keys.removeAll { it != myKeyValue }
d

Daniele B

06/02/2021, 2:23 PM
@ilya.gorbunov thanks! it works
e

ephemient

06/03/2021, 7:22 AM
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
5 Views