Sort map dictionary by value

This example will show how to sort a map or dictionary by value in groovy. If you have a domain, a table of key and values, you might want to display a drop down with the descriptions in order. If you can't sort via a database, a straight forward way is to sort the map by value. I pulled some sample values from gmail for mail actions.

We will use groovy spaceship operator which delegates to the Strings compareTo method. For sorting map by value in reverse order we just switched what we are comparing. In a comparable example we demonstrate how to sort maps by value in java, java 8 and guava.

Sort by value

@Test
void sort_map_by_value() {

    def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]

    assert [
        "Add to tasks",
        "Mark as important",
        "Mark as read",
        "More"] == myMap.sort({a, b -> a.value <=> b.value})*.value
}

Sort map in reverse

@Test
void sort_map_by_value_reverse() {

    def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]

    assert [
        "More",
        "Mark as read",
        "Mark as important",
        "Add to tasks"] == myMap.sort({a, b -> b.value <=> a.value})*.value
}

Sort map by value case insensitive

@Test
void sort_map_by_value_case_insensitive() {

    def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]

    assert [
        "Add to tasks",
        "Mark as important",
        "Mark as read",
        "More"] == myMap.sort({a, b -> a.value.toLowerCase() <=> b.value.toLowerCase()})*.value
}