Sortieren, ordnen Werte in absteigender Reihenfolge mit Groovy
Ich habe eine Map<String,Integer>
deren Einträge (Schlüssel) werden müssen, sortiert in der Reihenfolge der absteigend Wert. Zum Beispiel, wenn die Karte sieht aus wie:
"a" => 5
"b" => 3
"c" => 12
"d" => 9
Die nach der Sortierung muss es so Aussehen:
"c" => 12
"d" => 9
"a" => 5
"b" => 3
Mein bester Versuch bisher:
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}
}
Wenn ich test()
ich bekomme die folgende Ausgabe:
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.
Wo bin ich denn hier falsch?
- Meinst du die Werte Sortieren? Nicht die Tasten wie bei der Frage?
Du musst angemeldet sein, um einen Kommentar abzugeben.
Nur:
m.sort { -it.value }
compareTo
Methode. Siehe hier für die Dokumentation.Zu tun, die Sortierung, Tim Umsetzung ist der Weg zu gehen. Aber wenn Sie nur Fragen, warum dein Beispiel-code funktioniert nicht wie erwartet, die Antwort ist, dass die variable "sortiert" werden muss, vom Typ LinkedHashMap, anstatt nur HashMap. Sie können es explizit:
Oder, nur dazu: