Sort Map Entries By Value

Maps have no order, so copy entries into a slice and sort with SortFunc by value descending, using the key as a tiebreak for a stable ranked report.

GoData Integrity

Code

gosnippet
39 lines
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type RouteStat struct {
	Path string
	Hits int
}

func main() {
	traffic := map[string]int{
		"/api/orders": 42,
		"/api/users":  118,
		"/health":     300,
		"/metrics":    42,
	}

	// map 无法按值排序:先把键值对搬进切片
	entries := make([]RouteStat, 0, len(traffic))
	for path, value := range traffic {
		entries = append(entries, RouteStat{path, value})
	}

	// 按值降序,值相同再按路径升序,输出稳定
	slices.SortFunc(entries, func(a, b RouteStat) int {
		if a.Hits != b.Hits {
			return b.Hits - a.Hits
		}
		return cmp.Compare(a.Path, b.Path)
	})

	for rank, e := range entries {
		fmt.Printf("#%d %-12s %d hits\n", rank+1, e.Path, e.Hits)
	}
}

Sorting entries by their values

Sort Map Entries By Value reduces to the function main.

One loop does the cycling here: for path, value := range traffic.

Iteration is driven by for path, value := range traffic and for rank, e := range entries.

Statements that matter

entries = append(entries, RouteStat{path, value})
for rank, e := range entries {
	fmt.Printf("#%d %-12s %d hits\n", rank+1, e.Path, e.Hits)
}
entries := make([]RouteStat, 0, len(traffic))

Interactive Tools for This Topic

FAQ

How do you run Sort Map Entries By Value?
This is a complete program, not a library excerpt — execution starts at the top.