Tuesday, March 25, 2025

Golang how to sort the keys in a map and create a new array

Golang maps are purposely unordered. If you add the values "b": 2 and "a": 1 to a map, iterating this will sometimes get "a" first, and other times "b" first.

With many languages, they have data types like arrays or ordered maps that allow you to traverse the array in the order of keys. Others have a built a method to output a new array in key order.

Golang requires the use of a few helper methods to convert a map into a key sorted slice.

package main

import (
"fmt"
"maps"
"slices"
)

func main() {
fmt.Println("Start")

intStringMap := map[int]string{
2: "b",
1: "a",
3: "c",
}

// Two ways to get the keys from a map and sort them
// intKeys := slices.Collect(maps.Keys(intStringMap))
// sort.Ints(intKeys)
intKeys := slices.Sorted(maps.Keys(intStringMap))

sortedIntStringArray := make([]string, 0)

for _, key := range intKeys {
sortedIntStringArray = append(sortedIntStringArray, intStringMap[key])
}

fmt.Printf("%v\n", sortedIntStringArray) // [a b c]

stringIntMap := map[string]int{
"b": 2,
"a": 1,
"c": 3,
}

// Same as above but with a string int map
// stringKeys := slices.Collect(maps.Keys(stringIntMap))
// sort.Strings(stringKeys)
stringKeys := slices.Sorted(maps.Keys(stringIntMap))

sortedStringIntArray := make([]int, 0)

for _, key := range stringKeys {
sortedStringIntArray = append(sortedStringIntArray, stringIntMap[key])
}

fmt.Printf("%v\n", sortedStringIntArray) // [1 2 3]

fmt.Println("Done")
}



No comments: