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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.
FAQ
- How do you run Sort Map Entries By Value?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.