Home >Backend Development >Golang >How to Sort a Go Map by its Values?
Sorting a Map by its Values in Go
Sorting a map by its values in Go requires a custom implementation of the sort interface. Here's a solution that implements a PairList type and defines necessary functions for sorting:
<br>func rankByWordCount(wordFrequencies map[string]int) PairList {<br> pl := make(PairList, len(wordFrequencies))<br> i := 0<br> for k, v := range wordFrequencies {</p> <pre class="brush:php;toolbar:false">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] }
Using the rankByWordCount function, you can sort a map as follows:
<br>wordFrequencies := map[string]int{<br> "hello": 10,<br> "foo": 20,<br> "bar": 20,<br>}</p> <p>sortedPairs := rankByWordCount(wordFrequencies)</p> <p>for _, pair := range sortedPairs {<br> fmt.Println(pair.Key, pair.Value)<br>}<br>
Output:
<br>foo 20<br>bar 20<br>hello 10<br>
The above is the detailed content of How to Sort a Go Map by its Values?. For more information, please follow other related articles on the PHP Chinese website!