How to Sort a Map by Key in Go

1. Introduction

Maps in Go are inherently unordered. Sometimes you need to present the data sorted by keys or search through it in a specific order. This blog post will demonstrate how to sort a map by its keys in Go using the standard sort package.

2. Program Steps

1. Declare and initialize a map with some key-value pairs.

2. Extract the keys into a slice.

3. Sort the slice of keys using the sort.Strings method.

4. Iterate over the sorted keys to access values from the map.

5. Print each key-value pair in the order of the sorted keys.

3. Code Program

Sorting a map by keys involves extracting the keys into a slice, sorting the slice, and then iterating over the sorted keys to retrieve values from the map. This provides a sorted view of the map keys for presentation or processing.

Here is the complete Go program:
package main

import (
	"fmt"
	"sort"
)

func main() {
	// Step 1: Declare and initialize a map
	capitals := map[string]string{
		"United States": "Washington D.C.",
		"Japan":         "Tokyo",
		"France":        "Paris",
		"India":         "New Delhi",
	}

	// Step 2: Extract the keys into a slice
	keys := make([]string, 0, len(capitals))
	for key := range capitals {
		keys = append(keys, key)
	}

	// Step 3: Sort the slice of keys
	sort.Strings(keys)

	// Step 4: Iterate over the sorted keys
	fmt.Println("Capitals sorted by country name:")
	for _, key := range keys {
		// Step 5: Print each key-value pair
		fmt.Printf("%v: %v\n", key, capitals[key])
	}
}

Output:

Capitals sorted by country name:
France: Paris
India: New Delhi
Japan: Tokyo
United States: Washington D.C.

Explanation:

1. package main - Defines the package for the Go program.

2. import "fmt" and import "sort" - Import the necessary packages for printing and sorting.

3. capitals - A map from country names to their capitals is declared and initialized.

4. keys - A slice to store the map's keys is created, with an initial capacity equal to the number of entries in the map.

5. The for loop extracts each key from the map and appends it to the keys slice.

6. sort.Strings(keys) sorts the slice of keys alphabetically.

7. Another for loop iterates over the sorted keys, using each key to access and print its corresponding value from the map.

8. The output lists the capitals in alphabetical order by the country name, showing that the map has been successfully sorted by key.


Comments