How to sort a map by keys or values in Go?

To sort a map by keys or values in Go, you can follow the steps below:

  1. Import the necessary packages:
import ( "fmt" "sort" )
  1. Define a map with the desired key-value pairs.
myMap := map[string]int{ "banana": 2, "apple": 1, "kiwi": 3, }
  1. To sort the map by keys, create a slice of keys and use the sort.Strings() function to sort the keys.
var sortedKeys []string for key := range myMap { sortedKeys = append(sortedKeys, key) } sort.Strings(sortedKeys)
  1. To sort the map by values, create a slice of key-value pairs and use the sort.Slice() function to sort the slice based on the values using a custom comparison function.
var sortedPairs []struct { Key string Value int } for key, val := range myMap { sortedPairs = append(sortedPairs, struct { Key string Value int }{key, val}) } sort.Slice(sortedPairs, func(i, j int) bool { return sortedPairs[i].Value < sortedPairs[j].Value })
  1. Finally, iterate over the sorted keys or pairs and access the values from the original map.
fmt.Println("Sorted by keys:") for _, key := range sortedKeys { fmt.Println(key, myMap[key]) } fmt.Println("Sorted by values:") for _, pair := range sortedPairs { fmt.Println(pair.Key, pair.Value) }

This will print the map sorted by keys first and then by values.

Make sure to remember that maps in Go are inherently unordered, so sorting a map doesn't change the original map but rather creates a sorted representation of its contents.