How to sort map by key in Golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To sort map by key in Golang, first we have to create slice of map keys after this golang provide sort package, which we can to sort map in ascending or descending order.

  • For ascending alphabetical order sort.Strings(mapKeys)
  • For descending alphabetical order sort.Sort(sort.Reverse(sort.StringSlice(mapKeys)))

Today, I’m going show you how do i sort map by keys in Golang.

Let’s start

Sort map by keys in ascending order

Here, we will create sample map with data and use sort package to print map keys and values in map keys ascending order.

package main
 
import (
    "fmt"
    "sort"
)
 
func main() {
  domains := map[string]int{"infinitbility": 1, "aguidehub": 2,
                            "sortoutcode": 3, "gorepairhub": 4}

  keys := make([]string, 0, len(domains))

  for key := range domains {
      keys = append(keys, key)
  }

  sort.Strings(keys)

  for _, k := range keys {
      fmt.Println(k, domains[k])
  }
}

Here, sorted map keys string in ascending alphabetical order, let’s see the output.

Output:

aguidehub 2
gorepairhub 4
infinitbility 1
sortoutcode 3

Sort map by keys in descending order

Here, we will create sample map with data and use sort package to print map keys and values in map keys descending order.

package main
 
import (
    "fmt"
    "sort"
)
 
func main() {
  domains := map[string]int{"infinitbility": 1, "aguidehub": 2,
                            "sortoutcode": 3, "gorepairhub": 4}

  keys := make([]string, 0, len(domains))

  for key := range domains {
      keys = append(keys, key)
  }

   sort.Sort(sort.Reverse(sort.StringSlice(keys)))

  for _, k := range keys {
      fmt.Println(k, domains[k])
  }
}

Here, sorted map keys string in descending alphabetical order, let’s see the output.

Output:

sortoutcode 3
infinitbility 1
gorepairhub 4
aguidehub 2

Tip: try to same case string in keys like (each character lower case, uppercase)

All the best 👍