Given this code block
map[string]int {"hello":10, "foo":20, "bar":20}
I would like to print out
foo, 20 bar, 20 hello, 10
In the order of highest to lowest
Example: Sort a map by values Inside the method, we first created a list named capitalList from the map capitals . We then use the sort() method of Collections to sort elements of the list. The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.
We can use the sort() method of the List interface to sort the elements of Map. The sort() method sorts the elements into ascending order and we specified the sort by value by using the comparingByValue() method.
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.
You cannot sort a map by its values due to the implementation of the map.
Found the answer on Golang-nuts by Andrew Gerrand
You can implement the sort interface by writing the len/less/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] }
For the original post, please find it here https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With