【问题标题】:How to add age to ageList =[12,13,23]如何将年龄添加到 ageList =[12,13,23]
【发布时间】:2010-04-08 00:16:44
【问题描述】:

这个问题可能太简单了,但是......请帮忙

我有一个这样的列表:

def ageList =[12,13,23]

我想得到这个:

def newAgeList =[age:12,age:13,age:23]

有人能帮帮我吗?

非常感谢!

【问题讨论】:

    标签: list groovy


    【解决方案1】:

    这对你有用吗?

    def newAgeList = ageList.inject([:]) { map, item -> if (!map['age']) map['age'] = []; map['age'] << item; map }
    

    他的结果是:['age':[12, 13, 23]]

    否则,您可以获得如下文字值:

    def newAgeList = ageList.collect { "age:$it" }
    

    他的结果是:['age:12', 'age:13', 'age:23']

    第三种选择:

    def newAgeList = ageList.collect { ['age':it] }
    

    这将导致:[['age':12], ['age':13], ['age':23]]

    不幸的是,您不能像上面显示的那样作为地图执行此操作,因为地图键必须是唯一的。

    真的,这完全取决于您要对结果做什么。

    【讨论】:

      【解决方案2】:

      不知道这是否可行,因为您想对三个不同的值使用相同的映射键“年龄”。您最终会用新值覆盖现有值。

      【讨论】:

      • 谢谢!如何使用 List.add() 创建一个新列表? def rawLines = [1,2,3] def lines = [] rawLines.each { lines.add("good") } 我在上面试过了,没用..我只是在学习 groovy....
      猜你喜欢
      • 2019-10-31
      • 2023-03-11
      • 1970-01-01
      • 2016-06-08
      • 2020-01-03
      • 2020-10-08
      • 2023-01-29
      • 1970-01-01
      • 2018-09-30
      相关资源
      最近更新 更多