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

How Can I Sort a Go Map by Its Integer Values in Descending Order?

Susan Sarandon
Release: 2024-12-10 13:56:15
Original
170 people have browsed it

How Can I Sort a Go Map by Its Integer Values in Descending Order?

Sorting Map Values in Go

In Go, a given map where keys are of type string and values are of type int can be sorted based on its values in descending order.

Problem Statement:

Consider the following map:

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

The goal is to print the sorted key-value pairs as:

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

Implementation:

To achieve this sorting, an implementation of the Go sort interface is necessary. This is done by defining the Len(), Less(), and 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] }
Copy after login

Conclusion:

By implementing the sort interface and leveraging the sort.Reverse function, maps can be effectively sorted by their values in Go, enabling various sorting scenarios.

The above is the detailed content of How Can I Sort a Go Map by Its Integer 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