2014-09-04 136 views
5

我有一個Map<String,Integer>其條目(鍵)需要按照的降序排列值排序。例如,如果地圖上的樣子:按照Groovy的降序排序Map值

"a" => 5 
"b" => 3 
"c" => 12 
"d" => 9 

排序之後,它需要看起來像:

"c" => 12 
"d" => 9 
"a" => 5 
"b" => 3 

我最好迄今爲止嘗試:

def test() { 
    Map<String,Integer> toSort = new HashMap<String,Integer>() 
    toSort.put("a", 5) 
    toSort.put("b", 3) 
    toSort.put("c", 12) 
    toSort.put("d", 9) 

    Map<String,Integer> sorted = sortMapDesc(toSort) 
    sorted.each { 
     println "${it.key} has a value of ${it.value}." 
    } 
} 

def sortMapDesc(Map<String,Integer> toSort) { 
    println "Sorting..." 
    println toSort 

    // The map of properly sorted entries. 
    Map<String,Integer> sorted = new HashMap<String,Integer>() 

    // Keep scanning the map for the key with the highest value. When we find 
    // it, add it as the next entry to the 'sorted' map, and then zero it out 
    // so it won't show up as the highest on subsequent scans/passes. Stop scanning 
    // when the entire 'toSort' map contains keys with zeros. 
    while(!mapIsAllZeros(toSort)) { 
     int highest = -1 
     String highestKey = "" 
     toSort.each { 
      if(it.value > highest) { 
       highest = it.value 
       highestKey = it.key 
      } 
     } 

     toSort.put(highestKey, 0) 
     sorted.put(highestKey, highest) 
    } 

    sorted 
} 

def mapIsAllZeros(Map<String,Integer> toCheck) { 
    toCheck.values().every{!it} 
} 

當我運行test()我得到以下輸出:

Sorting... 
[d:9, b:3, c:12, a:5] 
d has a value of 9. 
b has a value of 3. 
c has a value of 12. 
a has a value of 5. 

我在哪裏錯了?

+0

你的意思是值進行排序?不是問題中的關鍵? – 2014-09-04 23:36:53

回答

12

只要做到:

​def m = [a:​5, b:12, c:3, d:9] 
def sorted = m.sort { a, b -> b.value <=> a.value } 
+9

另一個選項是:'m.sort {-it.value}' – Steinar 2014-09-05 06:53:16

+0

@tim_yates嗨,你能解釋一下這個關閉是什麼意思,b - > b.value <=> a.value ..謝謝:) – user3714598 2015-12-04 04:43:05

+0

@ user3714598, '<=>'是「太空船操作員」。它委託給'compareTo'方法。有關文檔,請參閱[此處](http://docs.groovy-lang.org/latest/html/documentation/index.html#_spaceship_operator)。 – AutonomousApps 2016-05-04 16:10:12

1

來進行排序,Tim的實現是要走的路。但是如果你只是想知道爲什麼你的示例代碼不能像你期望的那樣工作,答案是變量'sorted'需要是LinkedHashMap類型,而不是HashMap。你可以明確地設置:

Map<String,Integer> sorted = new LinkedHashMap<String,Integer>() 

或者,只是這樣做:

Map<String,Integer> sorted = [:]