Edit See @tim's solution below for a “correct” Groovy approach to map recursion. Since Map findRecursive does not yet exist in Groovy, if you need this function in different parts of the application, just add it to Map metaClass:
Map.metaClass.findRecursive = {String key-> if(delegate.containsKey(key)) return delegate."$key" else for(m in delegate) { if(m.value in Map) return m.value.findRecursive(key) } }
Original I hope that something like findResult {it.key == 'foo'} will be overwritten through map elements beyond the depth of 1 d, but it seems to be wrong.
Scrolled my own recursive map finder, but I wonder if there is a better way to do this. Maybe there is a built-in function that I miss, or even a Groovier (compressed) way to remove from below:
Map map = [school:[id:'schoolID', table:'_school', children:[team:[id:'teamID',table:'_team', children:[player:[id:'playerID',table:'_roster']] ]] ]] class Foo { static finder = {Map map, String key-> if(map.containsKey(key)) return map[key] else for(m in map) { if(m.value in Map) return this.finder(m.value,key) } } } println Foo.finder(map,'team')
source share