Accessing elements of a map of maps using a string in Groovy

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Given I have a map like:

def myMap = [ b : [ c:"X" ] ]

And a string

def key =  b.c 

I d like to see my options for using the key to get to the value X .

I have come up with two ways of achieving this myself, but I am not very happy with these solutions:

 1) Eval.me("theMap", myMap, "theMap.$key")
 2) mayMap."$key.split( \. )[0]"."$key.split( \. )[1]"

Anyone has a better way of doing this in Groovy?

Answers

http://groovy.codehaus.org/gapi/groovy/util/ConfigObject.html http://groovy.codehaus.org/gapi/groovy/util/ConfigObject.html

def myMap = [b:[c: X , d:  Y ], a:[n:[m:[x: Y ]]]] as ConfigObject
def props = myMap.toProperties()

assert props[ b.c ] ==  X 
assert props. b.c  ==  X 
assert props. a.n.m.x  ==  Y 
  Pros:     
    • No more splitting.
    • No more evaluating.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/17437561/accessing-elements-of-a-map-of-maps-using-a-string-in-groovy

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils