【问题标题】:retaining all the values of a key value search in groovy保留groovy中键值搜索的所有值
【发布时间】:2013-12-13 23:03:20
【问题描述】:

我有一个声明

There are couple of values which satisfies the search criteria, but the first value is overwritten by the second and I could see only one value.

我需要使用不同的数据类型吗?

例子:

我的列表如下:

[ [ name1:a, name2:b, name3:c, name4:d, other:1, other1:2 ],
  [ name1:a, name2:a, name3:b, name4:c, other:3, other1:4],  
  [ name1:a, name2:b, name3:c, name4:d, other:2, other1:3] ]

所以我想要的是 name1、name2、name3、name4 的 groupBy

--> 我们有 [other:1, other1:2] 和 [other:2, other1:3]

是否可以在 groupBy 中包含多个键?

【问题讨论】:

    标签: groovy


    【解决方案1】:

    Maps 每个键只能有一个条目。

    不过,您可以拥有地图的值列表,例如 [ key:[ val1, val2 ] ]

    如果您的原始数据在地图列表中,也许groupBy 会有所帮助?即:

    def data = [ [ name:'a', value:1 ],
                 [ name:'b', value:1 ],
                 [ name:'a', value:1 ] ]
    
    def result = data.groupBy { it.name }
    
    assert result == [ a:[ [ name:'a', value:1 ],
                           [ name:'a', value:1 ] ],
                       b:[ [ name:'b', value:1 ] ] ]
    
    assert result.a == [ [ name:'a', value:1 ], [ name:'a', value:1 ] ]
    

    使用您的示例,您可以:

    def list = [ [ name1:'a', name2:'b', name3:'c', name4:'d', other:1, other1:2 ],
                 [ name1:'a', name2:'a', name3:'b', name4:'c', other:3, other1:4],  
                 [ name1:'a', name2:'b', name3:'c', name4:'d', other:2, other1:3] ]
    
    list.groupBy { [ name1:it.name1, name2:it.name2, name3:it.name3, name4:it.name4 ] }.collectEntries { k, v ->
        [ k, v.collect { [ other:it.other, other1:it.other1 ] } ]
    }
    

    这会给你输出地图:

    [ ['name1':'a', 'name2':'b', 'name3':'c', 'name4':'d']:[['other':1, 'other1':2], ['other':2, 'other1':3]],
      ['name1':'a', 'name2':'a', 'name3':'b', 'name4':'c']:[['other':3, 'other1':4]]]
    

    你的意思是这样的?

    编辑

    不使用collectEntries,这可能有效:

    list.groupBy { [ name1:it.name1, name2:it.name2, name3:it.name3, name4:it.name4 ] }
        .inject( [:] ) { map, key, value ->
            map[ key ] = value.collect { [ other:it.other, other1:it.other1 ] }
            map
    }
    

    【讨论】:

    • 感谢蒂姆的回复,是否可以在组中包含多个键(我正在用一个例子编辑我的问题)
    • 我的意思是同一个蒂姆,但我的版本是 1.5.6,所以我相信 collectEntries 或 collect 不起作用...
    • @Techie 哦...已经超过 5 年了...不能升级?
    • 这是我们的限制蒂姆,我们正在使用 groovy 作为自定义工具之一中的脚本 :-)
    • 能否请您告诉我如何在不使用 collectEntries 的情况下检索结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多