I have a Map<String,Integer> whose records (keys) need to be sorted in descending order. For example, if the map looks like this:
"a" => 5 "b" => 3 "c" => 12 "d" => 9
After sorting it should look like this:
"c" => 12 "d" => 9 "a" => 5 "b" => 3
My best attempt:
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
When I run test() , I get the following output:
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.
Where am I wrong here?
smeeb source share