2014-09-04 19 views
5

Mam Map<String,Integer> Mam wpisy (klucze) należy posortować w kolejności malejąco wartość. Na przykład, jeśli mapa wygląda następująco:Sortowanie wartości mapy w porządku malejącym z Groovy

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

After sortowania musi wyglądać następująco:

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

moja najlepsza próba dotąd:

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} 
} 

Kiedy uruchamiam test() I Uzyskaj następujące dane wyjściowe:

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. 

Gdzie ja się tu mylę?

+0

To znaczy, posortować wartości? Nie klucze jak w pytaniu? –

Odpowiedz

12

Wystarczy zrobić:

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

Inną opcją jest po prostu: 'm.sort {-it.value}' – Steinar

+0

@tim_yates hi, czy możesz wyjaśnić, co to zamknięcie oznacza a, b -> b.value <=> a.value .. thanks :) – user3714598

+0

@ user3714598, '<=>' jest "operatorem statku kosmicznego". Przekazuje do metody 'compareTo'. Zobacz dokument [tutaj] (http://docs.groovy-lang.org/latest/html/documentation/index.html#_spaceship_operator). – AutonomousApps

1

Aby wykonać sortowanie, realizacja Tima jest droga. Ale jeśli zastanawiasz się, dlaczego twój przykładowy kod nie działa tak, jak oczekujesz, odpowiedź brzmi, że zmienna "posortowana" musi być typu LinkedHashMap, a nie tylko HashMap. Można ustawić go wyraźnie:

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

Albo, po prostu to zrobić:

Map<String,Integer> sorted = [:] 
Powiązane problemy