Reputation: 315
Is there a Groovy way of dropping elements from a
that match values in b
?
def a = [1:"aa", 2:"bb", 3:"cc", 4:"dd"]
def b = [ "bb", "dd"]
expected output : [1:"aa", 3:"cc"]
I am currently using 2 nested for loops to solve this. I am wondering if Groovy has a better way of doing it?
Upvotes: 1
Views: 678
Reputation: 42184
2.5.0
You can use a single Map.findAll()
method to do that:
a.findAll { k,v -> !(v in b) }
However, keep in mind that this method does not modify existing a
map, but it creates a new one instead. So if you want to modify map stored in a
variable you will have to reassign it.
a = a.findAll { k,v -> !(v in b) }
2.5.0
Groovy version 2.5.x introduced a new default method for Map
- removeAll
which takes a predicate and removes elements from input map based on this predicate.
a.removeAll { k,v -> v in b}
Upvotes: 2