【问题标题】:Does groovy have a built-in way to walk / transform a data structure?groovy 是否有内置的方式来遍历/转换数据结构?
【发布时间】:2019-10-20 13:12:56
【问题描述】:

给定 Groovy 中的嵌套映射/列表/标量数据结构,它是否有任何漂亮的“Groovy”方式来遍历它并生成转换后的结构?

到目前为止,我编写的最简洁的方式还不错,它是一个应用闭包的递归遍历器。但是,如果我缺少一种内置方式,我会欢迎您提出建议。

例如,取这个数据结构并将其中的Strings 中的${VARIABLE} 的所有实例替换为REPLACED

def config = [
  '${VARIABLE}: 'scalar',
  'foo': [
    'bar': 1,
    'baz': ['a', 'b', 'c', 'd'],
    'my_${VARIABLE}_key': null
  ],
  'bak': 1,
  'ban': 'abcd',
  'boo': [
    ['x': 1, 'y': 2, 'subst': '${VARIABLE}'],
    ['a': 1, 'b': 2]
  ]
]

【问题讨论】:

    标签: list dictionary data-structures groovy traversal


    【解决方案1】:

    这是迄今为止我想出的最好的:

    def walk(v, Closure transform ) {
      switch (v) {
        case null:
          return null
        case Map:
          return v.collectEntries { mk, mv -> [ transform(mk), walk(mv, transform) ] }
        case List:
          return v.collect { lv -> walk(lv, transform) }
        default:
          return transform(v)
      }
    }
    

    根据上述示例数据,可以这样应用:

    def engine = new groovy.text.SimpleTemplateEngine()
    
    def subs = ['VARIABLE': 'REPLACED']
    
    def newconfig = walk(config) { v ->
      switch (v) {
          case String:
            return engine.createTemplate(v).make(subs)
          default:
            return v
      }
    }
    

    这依赖于 Groovy 的智能 switch 语句。它不可扩展,你不能只插入你自己的类型处理程序,但它非常简单,你不需要。默认情况下,它会进行混合复制,创建 Lists 和 Maps 的新实例,但保留对原始标量或不匹配类型的引用。根据以下身份转换示例,它也可以进行深度复制:

    // Identity transform, shallow copy scalars
    assert (config == (walk(config) { v -> v.clone() }))
    
    // Identity transform, deep copy scalars where possible
    assert (config == (walk(config) {
      v ->
      try {
        return v.clone()
      } catch (java.lang.CloneNotSupportedException ex) {
        return v
      }
    }))
    

    想法?更好的方法?

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多