Reputation: 2025
Have a Mutable Map like this
val orders: MutableMap<Int, MutableList<MenuItem>>
How can I delete first element of it or remove all by filter?
Upvotes: 0
Views: 2898
Reputation: 127
I needed to remove a certain number of elements from a map - didn't matter which ones. This worked for me:
orders.remove(orders.keys.first())
For removing all matching a filter, @Roland has given the various APIs you can use. e.g. to remove all entries having empty list as value:
orders.entries.removeAll { it.value.isEmpty() }
Upvotes: 0
Reputation: 23242
Regarding the "remove all by filter" you may be interested in one of the following:
orders.entries.removeIf { /* your predicate */ }
orders.values.removeIf { /* your predicate */ }
orders.keys.removeIf { /* your predicate */ }
// and/or the extension function removeAll:
orders.entries.removeAll { /* your predicate */ }
orders.values.removeAll { /* your predicate */ }
orders.keys.removeAll { /* your predicate */ }
Regarding removing the first I assume you just want any (but at most 1) matching element to remove (not the actual first in a Map
). You could probably just iterate/filter, take the first and then simply call remove
for it..., e.g.:
val yourMatchingEntry = orders.entries.first { /* your predicate */ }
.also { orders.entries.remove(it) }
This then just returns any (but 1) of the map entries which match your predicate.
Upvotes: 3