How to Sort Golang Map By Keys or Values?


Go is a powerful programming language that comes with built-in support for maps. Maps are unordered collections of key-value pairs, and sometimes it's necessary to sort them by either their keys or values. Fortunately, Go provides a way to sort maps by both keys and values using the sort package. In this article, we'll discuss how to sort a Golang map by keys or values.

Sort Golang Map By Keys

To sort a Golang map by keys, we first need to extract the keys from the map and sort them using the sort package. We can then iterate over the sorted keys and retrieve their corresponding values from the map.

Example

Here's an example of how to sort a Golang map by keys −

package main

import (
   "fmt"
   "sort"
)

func main() {
   m := map[string]int{
      "foo": 2,
      "bar": 1,
      "baz": 3,
   }

   // Extract keys from map
   keys := make([]string, 0, len(m))
   for k := range m {
      keys = append(keys, k)
   }

   // Sort keys
   sort.Strings(keys)

   // Print sorted map
   for _, k := range keys {
      fmt.Printf("%s: %d\n", k, m[k])
   }
}

Output

bar: 1
baz: 3
foo: 2

In the above example, we create a map with string keys and integer values. We then extract the keys from the map and sort them using the sort.Strings() function. Finally, we iterate over the sorted keys and print out the corresponding values from the map.

Sort Golang Map By Values

To sort a Golang map by values, we need to create a slice of key-value pairs and sort it based on the values. We can then extract the sorted keys from the slice.

Example

Here's an example of how to sort a Golang map by values −

package main

import (
   "fmt"
   "sort"
)

func main() {
   m := map[string]int{
      "foo": 2,
      "bar": 1,
      "baz": 3,
   }

   // Create slice of key-value pairs
   pairs := make([][2]interface{}, 0, len(m))
   for k, v := range m {
      pairs = append(pairs, [2]interface{}{k, v})
   }

   // Sort slice based on values
   sort.Slice(pairs, func(i, j int) bool {
      return pairs[i][1].(int) < pairs[j][1].(int)
   })

   // Extract sorted keys
   keys := make([]string, len(pairs))
   for i, p := range pairs {
      keys[i] = p[0].(string)
   }

   // Print sorted map
   for _, k := range keys {
      fmt.Printf("%s: %d\n", k, m[k])
   }
}

Output

bar: 1
foo: 2
baz: 3

In the above example, we create a map with string keys and integer values. We then create a slice of key-value pairs and sort it based on the values using the sort.Slice() function and a custom less function. Finally, we extract the sorted keys from the slice and print out the corresponding values from the map.

Conclusion

Sorting a Golang map by keys or values is easy with the sort package. By extracting and sorting the keys or creating a slice of key-value pairs and sorting it based on the values, you can sort a map in either ascending or descending order.

Updated on: 25-Apr-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements