【发布时间】:2011-05-31 19:16:08
【问题描述】:
编辑 请参阅下面的@tim 解决方案,了解映射递归的“正确”Groovy 式方法。由于 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')
原创 希望像 findResult{it.key=='foo'} 这样的东西会递归超过一维深度的地图元素,但似乎并非如此。
推出了我自己的递归地图查找器,但我想知道是否有更好的方法来做到这一点。也许我缺少一个内置函数,或者是一种更 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')
【问题讨论】: