Austin Gebauer

Software Engineer | Seattle, WA


Sorting maps in Go

Published January 6, 2020

Go provides a built-in map type that implements a hash table (i.e., associative array that can map keys to values).

When iterating over a map, the iteration order isn't specified and has no guarantee to be the same from one iteration to the next. So, if you require a certain iteration order, you'll need to create a separate data structure that specifies that order.

In this post, I'll show examples of how to specify that iteration order. I'll first present a problem and next show examples of how to solve it by sorting the contents of a map by key and/or value.

Example Problem

Imagine that we have a set of movie titles, each with an association to the number of likes the movie has received.

Title Likes
Alien Covenant 202
The Imitation Game 98
Spaceballs 146
Good Will Hunting 98

Our user would like to be able to sort by the movies by title (key), likes (value), or both the title and likes when a tie occurs.

The examples below show how to accomplish each one of these sorting tasks given the example association in a Go map.

Sorting Go Maps by Key

In this example, notice that the movie titles printed to standard out are sorted alphabetically in ascending order.

Sorting Go Maps by Value

In this example, notice that the movie likes printed to standard out are sorted numerically in ascending order.

Sorting Go Maps by both Key and Value

In this example, notice that the movie likes printed to standard out are sorted numerically in ascending order.

Also notice that when there is a tie in likes (value), the ordering falls back on movie title (key), which places Good Will Hunting before The Imitation Game.