2

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

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

如何以时髦的方式做到这一点?

4

1 回答 1

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 )

默认情况下,sortGroovy 中的方法会更改原始 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 ]

因此,如果您传递falsesort,它将单独保留原始列表,并仅返回排序列表:

// 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 ]
于 2013-10-01T08:54:44.437 回答