Groovy :: Map Find Recursive

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) } } // then anywhere in your app someMap.findRecursive('foo') 

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') 
+4
source share
1 answer

With Groovy 1.8 (reqd for the findResult method), you can do something like this:

 class DeepFinder { static Object findDeep( Map map, Object key ) { map.get( key ) ?: map.findResult { k, v -> if( v in Map ) v.findDeep( key ) } } } use( DeepFinder ) { println map.findDeep( 'team' ) } 

There is no Groovy default recursive method that I know of ...

+10
source

All Articles