Sort map by it’s keys in go

Hi guys,
this is day 12 out of 100 days of code. I didn’t post for a while, because I did a small break for hackaton, but now I am back on track.

When you print a map using range function it will access elements in randomized order. So, if you want to print map in sorted order you have to sort keys first. See how:

package main

import (

func main() {
	m := map[string]int{"A": 1, "B": 2, "AA": 1, "C": 3, "BBB": 2}

	//reverse keys and values of m map
	var mapKeys []string
	for k, v := range m {
		fmt.Printf("%s -> %d\n", k, v)
		mapKeys = append(mapKeys, k)

	for _, v := range mapKeys {
		fmt.Printf("%s -> %d\n", v, m[v])

Solution is to use additional array for keys and sort it in wished order.

Happy coding!