【问题标题】:Groovy :: Map Find RecursiveGroovy :: Map Find Recursive
【发布时间】: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') 

【问题讨论】:

    标签: recursion groovy map find


    【解决方案1】:

    使用 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 方法...

    【讨论】:

    • +1 @tim,不错的替代解决方案。 (Map)m.findRecursive('foo') 将是对 Groovy.lang 的一个很好的补充,imo。
    • @virtual,我同意...也许为 DGM 提供一个补丁,进行一些测试,然后将它们提交给 JIRA?可能会进入 1.8.2
    • 对,可以先在 Groovy 用户上发布此内容,这可能是尚未实施的原因。与此同时,编辑了我的帖子,将递归查找器添加到 Map metaClass(来自可怕的 LAMP 堆栈,拥有你的蛋糕并吃掉它真是太棒了;--))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多