Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a Given Key from a Groovy Map

I'm sure this is a very simple question, but I'm very new to Groovy and it's something I've been struggling with for awhile now. I have an HttpServletRequest and I need to do something with it's parameters. However, I want to exclude exactly 1 parameter.

Previously, I was using

req.getParameterMap

However, to remove the one value, I'm trying something along the lines of

def reqParams = req.getParameterMap?.remove('blah');

I know that the above does not quite work, but that's the psuedo-code for what I'm trying to achieve. I really need the new Map and the original req.getParameterMap() Objects to look exactly the same except for the one missing key. What's the best way to achieve this? Thanks!

like image 930
JToland Avatar asked May 31 '13 15:05

JToland


People also ask

How do I get rid of multiple keys on a map?

Assuming your set contains the strings you want to remove, you can use the keySet method and map. keySet(). removeAll(keySet); . keySet returns a Set view of the keys contained in this map.

How do I iterate a map in Groovy?

If you wanted to do it that way, iterate over map. keySet() and the rest will work as you expected. It should work if you use s. key & s.


2 Answers

req.getParameterMap returns an immutable map which cannot be modified. You need to create a new map, putAll from the parameter map and remove the required key you do not want.

def reqParams = [:] << req.getParameterMap() reqParams.remove('blah') 

You have your new map as reqParams (without the undesired key value pair) and the original parameter map.

like image 132
dmahapatro Avatar answered Oct 02 '22 11:10

dmahapatro


You can use findAll function, somethig like:

def map = req.getParameterMap().findAll {it.key != 'blah'} 
like image 21
rsa Avatar answered Oct 02 '22 13:10

rsa