Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a Map[string]int by its values?

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

like image 463
samol Avatar asked Sep 09 '13 09:09

samol


People also ask

How do you sort a map according to values?

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.

Can you sort a map by value in Java?

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.

Does map sort by key or value?

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.

Can we sort map in C++ by value?

You cannot sort a map by its values due to the implementation of the map.


1 Answers

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

like image 78
samol Avatar answered Sep 22 '22 21:09

samol