Skip to content

Instantly share code, notes, and snippets.

@souvikhaldar
Created July 28, 2020 18:48
Show Gist options
  • Save souvikhaldar/e542e2d88185f2ead0bb473264195062 to your computer and use it in GitHub Desktop.
Save souvikhaldar/e542e2d88185f2ead0bb473264195062 to your computer and use it in GitHub Desktop.
Sort a map of string to int type, by decending order of the value of the map.
package main
func ConvertMapToKVSlice(m map[string]int) (kv []KV) {
for k, v := range m {
kv = append(kv, KV{k, v})
}
return
}
type KV struct {
Key string
Value int
}
// SortedMapByValue is a sorted map by decreasing value
// POC- https://play.golang.org/p/mZN4uSa5pG0
type SortedMapByValue []KV
// Len is the number of elements in the collection.
func (s SortedMapByValue) Len() int {
return len(s)
}
// Less reports whether the element with
// index i should sort before the element with index j.
// we want it to be in decreasing order of the values
func (s SortedMapByValue) Less(i int, j int) bool {
return s[i].Value > s[j].Value
}
// Swap swaps the elements with indexes i and j.
func (s SortedMapByValue) Swap(i int, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SortedMapByValue) FetchKey(pos int) string {
if len(s) < pos {
return ""
}
return s[pos].Key
}
func (s SortedMapByValue) FetchVal(pos int) int {
if len(s) < pos {
return 0
}
return s[pos].Value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment