manish
manish

Reputation: 315

Remove map entries based on collection of values - how to do it in a Groovy way?

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

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

For Groovy < 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) }

For Groovy >= 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

Related Questions