Johan Johan - 4 years ago 283
Groovy Question

Return multiple values from map in Groovy?

Let's say I have a map like this:

def map = [name: 'mrhaki', country: 'The Netherlands', blog: true, languages: ['Groovy', 'Java']]

Now I can return "submap" with only "name" and "blog" like this:

def keys = ['name', 'blog']
// Will return a map with entries name=mrhaki and blog=true

But is there a way to easily return multiple values instead of a list of entries?


I'd like to do something like this (which doesn't work):

def values = map.{'name','blog'}

which would yield for example
['mrhaki', true]
(a list or tuple or some other datastructure).

Answer Source

You can iterate over the submap and collect the values:

def values = map.subMap(keys).collect {it.value}
// Result: [mrhaki, true]

Or, iterate over the list of keys, returning the map value for that key:

def values = keys.collect {map[it]}

I would guess the latter is more efficient, not having to create the submap.

A more long-winded way to iterate over the map

def values = map.inject([]) {values, key, value -> 
    if (keys.contains(key)) {values << value}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download