This example will demonstrate how to sort a map by keys. In the set up, we will create a HashMap with the key representing number of colaries burned and values being assoicated activities. For calories burned it will assume you weigh 200 pounds and performed an activity for 30 minutes. The conversion was provided by My FitnessPal exercise lookup. In a related example we demonstrate how to sort a dictionary by key in groovy.
Setup
TreeMap, a sorted map
This snippet will show how to sort a map by key using a TreeMap. TreeMap elements are sorted according to the natural ordering of its keys. It also has a constructor that accepts a Comparator as shown below.
Output
Treemap, specific order
This snippet will show how to sort a HashMap in decending order by passing in a comparator to the TreeMap's constructor.
Output
Treemap, specific order w/ guava ordering
Following behavior shown in the snippet above, this will use the TreeMap's constructor passing in a Comparator created with Guava's fluent Ordering utility showing how to sort a HashMap in reverse order.