在Groovy中对Map的值进行排序

时间:2013-10-01 08:51:03

标签: groovy

我有一张地图,其中一个键包含多个值

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' ] ] 

如何以常规的方式做到这一点?

1 个答案:

答案 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 ]