How to Sort a Map by Value in Go

1. Introduction

Sorting a map by its values is a task that can be necessary when you need to order elements by criteria other than their keys. Go does not inherently support sorting maps by values directly. However, with a few more steps, it can be accomplished using the sort package and a custom sort logic. This blog post will guide you through sorting a map by values in Go.

2. Program Steps

1. Create and populate a map.

2. Extract key-value pairs into a slice of structs.

3. Sort the slice of structs based on the values.

4. Print out the sorted key-value pairs from the slice.

3. Code Program

Sorting a map by value in Go involves creating a separate data structure to hold the map's key-value pairs, and then sorting that structure according to the values. This often requires the creation of a slice of value-key pairs or struct elements to apply custom sorting logic.

Here is the complete Go program to demonstrate how to sort a Map by values:
package main

import (
	"fmt"
	"sort"
)

// KeyValue holds a single key-value pair.
type KeyValue struct {
	Key   string
	Value int
}

func main() {
	// Step 1: Create and populate a map.
	rankings := map[string]int{
		"Alice": 2,
		"Bob":   1,
		"Claire": 3,
	}

	// Step 2: Extract key-value pairs into a slice of KeyValue.
	kvSlice := make([]KeyValue, 0, len(rankings))
	for k, v := range rankings {
		kvSlice = append(kvSlice, KeyValue{k, v})
	}

	// Step 3: Sort the slice based on the values.
	sort.Slice(kvSlice, func(i, j int) bool {
		return kvSlice[i].Value < kvSlice[j].Value
	})

	// Step 4: Print out the sorted key-value pairs.
	fmt.Println("Rankings sorted by score:")
	for _, kv := range kvSlice {
		fmt.Printf("%s has a score of %d\n", kv.Key, kv.Value)
	}
}

Output:

Rankings sorted by score:
Bob has a score of 1
Alice has a score of 2
Claire has a score of 3

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "sort" - Import statements for the Format package and the Sort package.

3. rankings - A map that stores names as keys and scores as values is declared and initialized.

4. KeyValue - A struct type to hold a single key-value pair from the map is defined.

5. kvSlice - A slice of KeyValue structs is created to store the map's key-value pairs.

6. A for loop populates kvSlice with the map's content.

7. sort.Slice is used to sort kvSlice by the Value field of KeyValue structs, defining an anonymous function for the less logic.

8. Another for loop iterates over the sorted kvSlice to print the ranking.

9. The output displays the sorted rankings according to the scores.


Comments