我的原始列表是:
[[string: firstString, id: 2],
[string: secondString, id: 1],
[string: secondString, id: 3],
[string: firstString, id: 1],
[string: firstString, id: 3],
[string: secondString, id: 2]]
我希望按字符串对其进行分组,然后按ID对其进行排序:
[[string: firstString, id: 1],
[string: firstString, id: 2],
[string: firstString, id: 3],
[string: secondString, id: 1],
[string: secondString, id: 2],
[string: secondString, id: 3]]
答案 0 :(得分:3)
def firstString = 'first'
def secondString = 'second'
def source =
[[string: firstString, id: 2],
[string: secondString, id: 1],
[string: secondString, id: 3],
[string: firstString, id: 1],
[string: firstString, id: 3],
[string: secondString, id: 2]]
您声明的预期结果:
def expected =
[[string: firstString, id: 1],
[string: firstString, id: 2],
[string: firstString, id: 3],
[string: secondString, id: 1],
[string: secondString, id: 2],
[string: secondString, id: 3]]
def result = source.sort { [it.string, it.id] }
assert result == expected
ID按顺序排序:
def expected =
[[string: firstString, id: 3],
[string: firstString, id: 2],
[string: firstString, id: 1],
[string: secondString, id: 3],
[string: secondString, id: 2],
[string: secondString, id: 1]]
def result = source.sort { [it.string, -it.id] }
assert result == expected
真正分组,不仅按字符串排序:
def expected =
[(firstString):
[[string: firstString, id: 1],
[string: firstString, id: 2],
[string: firstString, id: 3]],
(secondString):
[[string: secondString, id: 1],
[string: secondString, id: 2],
[string: secondString, id: 3]]]
def result = source.groupBy { it.string }
result.each { it.value.sort { it.id } }
assert result == expected
真正分组,不仅按字符串排序,ID反向排序:
def expected =
[(firstString):
[[string: firstString, id: 3],
[string: firstString, id: 2],
[string: firstString, id: 1]],
(secondString):
[[string: secondString, id: 3],
[string: secondString, id: 2],
[string: secondString, id: 1]]]
def result = source.groupBy { it.string }
result.each { it.value = it.value.sort { it.id }.reverse() }
assert result == expected
真正分组并且ID已经变平:
def expected =
[(firstString): [1, 2, 3],
(secondString): [1, 2, 3]]
def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort() }
assert result == expected
真正分组,ID变平,ID反向排序:
def expected =
[(firstString): [3, 2, 1],
(secondString): [3, 2, 1]]
def result = source.groupBy { it.string }
result.each { it.value = it.value.collect { it.id }.sort().reverse() }
assert result == expected