Home > Backend Development > Golang > How Do I Sort a Map by Its Values in Descending Order?

How Do I Sort a Map by Its Values in Descending Order?

Barbara Streisand
Release: 2024-12-12 11:59:10
Original
155 people have browsed it

How Do I Sort a Map by Its Values in Descending Order?

How to Sort a Map by Its Values

This question arises when dealing with a map where the goal is to sort the key-value pairs based on the values in descending order. For example, given a map like:

map[string]int{
    "hello": 10,
    "foo": 20,
    "bar": 20,
}
Copy after login

One may want to print the sorted pairs as follows:

foo, 20
bar, 20
hello, 10
Copy after login

Solution

A solution to this problem is to implement the sort interface by providing the necessary len, less, and swap functions. Here's an example implementation:

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] }
Copy after login

To use this function, pass the map as an argument to rankByWordCount, which will return a sorted list of the key-value pairs. You can then iterate over the list to print the sorted results.

The above is the detailed content of How Do I Sort a Map by Its Values in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template