Groovy - 在组的每个最后一个条目中插入字符串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Groovy - 在组的每个最后一个条目中插入字符串相关的知识,希望对你有一定的参考价值。
原始清单:
def list = [[category: "DLF", name: "some name one"],
[category: "EF", name: "some name two"],
[category: "RW", name: "some name five"],
[category: "EF", name: "some name four"],
[category: "DLF", name: "some name two"],
[category: "RW", name: "some name three"]]
有没有办法按类别对其进行分组并按类别进行排序,但应该正确排列为“EF”,“DLF”,“RW”,我还想在类别的每个最后一个索引中插入新元素,就像这样一:
def list = [[category: "EF", name: "some name two"],
[category: "EF", name: "some name four"],
[category: "EF", name: "others"],
[category: "DLF", name: "some name one"],
[category: "DLF", name: "some name two"],
[category: "DLF", name: "others"],
[category: "RW", name: "some name three"],
[category: "RW", name: "some name five"],
[category: "RW", name: "others"]]
答案
因此,您可以定义结果的顺序:
def requiredOrder = ['EF', 'DLF', 'RW']
然后,您可以对其他元素进行分组,排序和添加:
def result = list.groupBy { it.category }
.sort { requiredOrder.indexOf(it.key) }
.collectMany { k, v -> v + [category: k, name: 'others'] }
所需的结果将在变量result
中
另一答案
几乎与@tim_yates相同,但稍微更直接:
def requiredOrder = ['EF', 'DLF', 'RW']
def result = ( list + requiredOrder.collect{ [ category:it, name: "others"] } )
.sort{ requiredOrder.indexOf it.category }
以上是关于Groovy - 在组的每个最后一个条目中插入字符串的主要内容,如果未能解决你的问题,请参考以下文章