gpt4 book ai didi

recursion - Groovy::Map Find Recursive

转载 作者:行者123 更新时间:2023-12-04 02:11:51 25 4
gpt4 key购买 nike

编辑
有关映射递归的“正确”Groovy 式方法,请参阅下面的@tim 解决方案。由于 Map findRecursive 在 Groovy 中尚不存在,如果您发现自己在应用程序的各个部分都需要此功能,只需将其添加到 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'} 这样的东西会递归超过一维深度的 map 元素,但似乎并非如此。

滚动了我自己的递归 map 查找器,但我想知道是否有更好的方法来做到这一点。也许我缺少一个内置函数,或者甚至是 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')

最佳答案

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

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' )
}

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

关于recursion - Groovy::Map Find Recursive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com