In Go, a given map where keys are of type string and values are of type int can be sorted based on its values in descending order.
Consider the following map:
map[string]int{"hello": 10, "foo": 20, "bar": 20}
The goal is to print the sorted key-value pairs as:
foo, 20 bar, 20 hello, 10
To achieve this sorting, an implementation of the Go sort interface is necessary. This is done by defining the Len(), Less(), and Swap() functions:
func rankByWordCount(wordFrequencies map[string]int) PairList { pl := make(PairList, len(wordFrequencies)) i := 0 for k, v := range wordFrequencies { pl[i] = Pair{k, v} i++ } sort.Sort(sort.Reverse(pl)) return pl } type Pair struct { Key string Value int } type PairList []Pair func (p PairList) Len() int { return len(p) } func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value } func (p PairList) Swap(i, j int){ p[i], p[j] = p[j], p[i] }
By implementing the sort interface and leveraging the sort.Reverse function, maps can be effectively sorted by their values in Go, enabling various sorting scenarios.
The above is the detailed content of How Can I Sort a Go Map by Its Integer Values in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!