Sorting a Map by its Values
Given a map of strings to integers, it is desirable to sort the map by its values in descending order.
Solution:
Implementing a custom sorting interface can achieve this functionality. The following code provides all the necessary functions to sort a map by its values:
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] }
For example, using the given map:
m := map[string]int{"hello": 10, "foo": 20, "bar": 20}
The sorted output would be:
foo, 20 bar, 20 hello, 10
The above is the detailed content of How to Sort a String-Integer Map by Value in Descending Order in Go?. For more information, please follow other related articles on the PHP Chinese website!