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?
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With