Sort map dictionary by key

This example will show how to sort a map or dictionary by keys in groovy. We will create a map with keys representing candy bar manufactures and values as candy bars. In the snippets below we will use the spread operator *. which is used to invoke the Entry.getKey on each element in the map. This will allow us to easily compare the keys and show them in the unit test. In a comparable example we demonstrate how to order map by keys in java.

Sort map by keys

@Test
void sort_map_by_keys() {

    def myMap = ["Toms International":"Yankie Bar", "Mars":"3 Musketeers", "Nestlé": "Yorkie", "Hershey's":"Eat-more"]

    assert [
        "Hershey's",
        "Mars",
        "Nestlé",
        "Toms International"] == myMap.sort()*.key
}

Sort map by key in reverse Java 8

We will pass a java 8 comparator that will be the reverse of the natural ordering of Strings.

@Test
void sort_map_by_key_in_reverse() {

    def myMap = ["Toms International" : "Yankie Bar", "Mars" : "3 Musketeers", "Nestlé" : "Yorkie", "Hershey's" : "Eat-more"]

    assert [
        "Toms International",
        "Nestlé",
        "Mars",
        "Hershey's"         
        ] == myMap.sort(Collections.reverseOrder())*.key
            
}