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

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

问题描述

编辑
请参阅下面的@ tim的解决方案,使用正确的Groovy-esque方法来映射递归。由于Map findRecursive在Groovy中尚不存在,因此如果您发现自己需要在应用程序的各个部分需要此功能,只需将其添加到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'}会通过地图递归元素超过1-d深,但似乎不是这样。

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方法的reqd),您可以这样做:

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 :: Map查找递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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