To sort a map by keys or values in Go, you can follow the steps below:
import (
"fmt"
"sort"
)
myMap := map[string]int{
"banana": 2,
"apple": 1,
"kiwi": 3,
}
sort.Strings()
function to sort the keys.var sortedKeys []string
for key := range myMap {
sortedKeys = append(sortedKeys, key)
}
sort.Strings(sortedKeys)
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
})
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.