原始列表:
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"]]
答案 0 :(得分:2)
因此,您可以定义结果的顺序:
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
答案 1 :(得分:1)
与@tim_yates几乎相同,但稍微更直接:
def requiredOrder = ['EF', 'DLF', 'RW']
def result = ( list + requiredOrder.collect{ [ category:it, name: "others"] } )
.sort{ requiredOrder.indexOf it.category }