我有一张地图,其中一个键包含多个值
datamap = [ 'Antenna Software':[ 'Salarpuria', 'Cessna', 'Vrindavan Tech', 'Alpha Center' ],
'Ellucian':[ 'Malvern', 'Ellucian House', 'Residency Road'] ]
这里我需要按字母顺序对值进行排序
datamap = [ 'Antenna Software':[ 'Alpha Center', 'Cessna', 'Salarpuria', 'Vrindavan Tech' ],
'Ellucian':[ 'Ellucian House', 'Malvern', 'Residency Road' ] ]
如何以常规的方式做到这一点?
答案 0 :(得分:8)
你应该可以这样做:
def sortedMap = datamap.sort().collectEntries { k, v ->
[ k, v.sort( false ) ]
}
如果你不打算对地图的键进行排序,你可以摆脱最初的sort()
:
def sortedMap = datamap.collectEntries { k, v ->
[ k, v.sort( false ) ]
}
sort( false )
: By default, the sort
method in Groovy changes the original list,所以:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it
def b = a.sort()
// And the result is sorted
assert b == [ 1, 2, 3 ]
// BUT the original list has changed too!
assert a != [ 3, 1, 2 ] && a == [ 1, 2, 3 ]
所以if you pass false
to sort
,它只留下原始列表,只返回已排序的列表:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it (passing false)
def b = a.sort( false )
// And the result is sorted
assert b == [ 1, 2, 3 ]
// AND the original list has remained the same
assert a == [ 3, 1, 2 ]