Removing a Given Key from a Groovy Map

57,510

Solution 1

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.

Solution 2

You can use findAll function, somethig like:

def map = req.getParameterMap().findAll {it.key != 'blah'}
Share:
57,510

Related videos on Youtube

JToland
Author by

JToland

Professional Software Development Engineer. SOreadytohelp

Updated on August 11, 2020

Comments

  • JToland
    JToland almost 4 years

    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!

    • Mr. Cat
      Mr. Cat almost 11 years
      Do you use grails or just add groovy support to your java app?
    • JToland
      JToland almost 11 years
      Just being used within a java app.
  • Mark Florence
    Mark Florence about 5 years
    I like this answer much better as it is easily generalized (for example) to remove all keys beginning with blah, as in: def map = req.getParameterMap().findAll {!it.key.startsWith('blah')}
  • Renato
    Renato almost 3 years
    Nice, but it's a real pitty they didn't make map - key work also :D (notice that map - [key: 'value'] works but you need to know the value, not just the key)