Groovy :: 映射查找递归 [英] Groovy :: Map Find Recursive

查看:36
本文介绍了Groovy :: 映射查找递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑请参阅下面的@tim 解决方案,了解映射递归的正确"Groovy 式方法.由于 Groovy 中尚不存在 Map findRecursive,如果您发现自己在应用程序的各个部分都需要此功能,只需将其添加到 Map metaClass:

Edit See @tim's solution below for the "correct" Groovy-esque approach to map recursion. Since Map findRecursive does not yet exist in Groovy, if you find yourself needing this functionality in various parts of your app, 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')

原创希望像 findResult{it.key=='foo'} 这样的东西会递归超过一维深度的地图元素,但似乎并非如此.

Original Was hoping something like findResult{it.key=='foo'} would recurse through map elements beyond 1-d deep, but appears not to be the case.

推出了我自己的递归地图查找器,但我想知道是否有更好的方法来做到这一点.也许我缺少一个内置函数,或者是一种更 Groovier(简洁)的方式来完成以下操作:

Rolled my own recursive map finder, but am wondering if there's a better way to do this. Maybe there's a built-in function I'm missing, or an even Groovier (concise) way to pull off the 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') 

推荐答案

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

With Groovy 1.8 (reqd for the findResult method), you could 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' )
}

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

There's no recursing default Groovy method that I know of...

这篇关于Groovy :: 映射查找递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆