Sorting and Inverting a Map
This lesson covers important details on sorting and inverting a map.
We'll cover the following...
Sorting a map
By default, a map is not sorted, not even on the value of its keys. If you want a sorted map, copy the keys (or values) to a slice, sort the slice (using the sort package), and print out the keys and/or values using the for-range on the slice. This is illustrated in the following program:
package mainimport ("fmt""sort")var (barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87,"echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kilo":43, "lima": 98})func main() {fmt.Println("unsorted:")for k, v := range barVal {fmt.Printf("key: %v, value: %v / ", k, v) // read random keys}keys := make([]string, len(barVal)) // storing all keys in separate slicei := 0for k := range barVal {keys[i] = ki++}sort.Strings(keys) // sorting the keys slicefmt.Println()fmt.Println("\nsorted:")for _, k := range keys {fmt.Printf("key: %v, value: %v / ", k, barVal[k]) // reading key from keys and value from barVal}}
In the code above, outside main
at line 4, we import sort
package to perform sorting, and at line 7, we make a map barVal
. The declaration of barVal
shows that its keys will be of string type and values associated with its keys will be of int type. The initialization is done at the same line. For example, the key alpha
gets value 34, bravo
get 56, charlie
gets 23 and so on.
In main
, we have a for-loop at line 15. This loop ...