Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shallow copy all but one entry from groovy map

Tags:

map

groovy

I need to shallow copy all entries in a Groovy map except for one, for which I already know the key. I prefer immutable and succinct approaches, and the minus() method is a pretty good fit except that providing the key isn't sufficient, and I would have to do something like this:

def map = [a:"aa", b:"bb"]

def knownKey = "a"
def result = map - [(knownKey):map[knownKey]]
assert result == [b:"bb"]

Alternatively I could give up (temporarily) on immutability and call the remove() method with the key as argument.

Is there a groovy'er approach I could take?

like image 625
Erik Madsen Avatar asked Sep 04 '14 19:09

Erik Madsen


1 Answers

You should use findAll as below:

def map = [a:"aa", b:"bb"]
def knownKey = "a"
def result = map.findAll { it.key != knownKey }
assert result == [b:"bb"]
like image 163
Opal Avatar answered Sep 28 '22 00:09

Opal