Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added examples for finding keys in a Map by value


Code Block
def m= [1:'a', 2:'b', 3:'c', 4:'d', 5:'e']
assert [86: m, 99: 'end'].clone()[86].is( m ) //clone() makes a shallow copy

def c= []
def d= ['a', 'bb', 'ccc', 'dddd', 'eeeee']
assert m.collect{ it.value * it.key } == d
assert m.collect(c){ it.value * it.key } == d
assert c == d

assert m.findAll{ it.key == 2 || it.value == 'e' } == [2:'b', 5:'e']
def me= m.find{ it.key % 2 == 0 }
assert [me.key, me.value] in [ [2,'b'], [4,'d'] ]

assert m.toMapString() == '[1:"a", 2:"b", 3:"c", 4:"d", 5:"e"]'

def sm= m.subMap( [2,3,4] )
sm[3]= 'z'
assert sm == [2:'b', 3:'z', 4:'d']
assert m == [1:'a', 2:'b', 3:'c', 4:'d', 5:'e'] //backing map is not modified

assert m.every{ it.value.size() == 1 }
assert m.any{ it.key % 4 == 0 }

Getting Map key(s) from a value.

Code Block

def family = [dad:"John" , mom:"Jane", son:"John"]

def val = "John"

The simplest way to achieve this with the previous map:

Code Block

assert family.find{it.value == "John"}?.key == "dad"
assert family.find{it.value == val}?.key == "dad"

Note that the return is only the key dad. As you can see from the family Map both dad and son are keys for the same values.

So, let's get all of the keys with the value "John"
Basically, findAll returns a collection of Mappings with the value "John" that we then iterate through and print the key if the key is groovy true.

This will place your results for the keys into a List of keys

Code Block

def retVal = []
family.findAll{it.value == val}.each{retVal << it?.key}

assert retVal == ["son", "dad"]

If you just wanted the collection of Mappings:

Code Block

assert family.findAll{it.value == val} == ["son":"John", "dad":"John"]
def returnValue = family.findAll{it.value == val}
assert returnValue == ["son":"John", "dad":"John"]

Special Notations

We can use special notations to access all of a certain key in a list of similarly-keyed maps: