Groovy :: Map Find Recursive

vir*_*yes 4 recursion groovy map find

编辑 请参阅下面的@ tim's解决方案,了解用于映射递归的"正确"Groovy-esque方法.由于Groovy中尚不存在Map findRecursive,如果您发现自己需要在应用程序的各个部分使用此功能,只需将其添加到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')
Run Code Online (Sandbox Code Playgroud)

原来 希望像findResult {it.key =='foo'}这样的东西可以通过超过1-d深度的地图元素进行递归,但似乎并非如此.

滚动我自己的递归地图查找器,但我想知道是否有更好的方法来做到这一点.也许有一个我缺少的内置函数,或者甚至是Groovier(简洁)的方法来实现以下功能:

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') 
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 10

使用Groovy 1.8(findResult方法的reqd),您可以执行以下操作:

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' )
}
Run Code Online (Sandbox Code Playgroud)

我知道没有递归的默认Groovy方法......