はじめに
Go のマップを値でソートされた順でキーを出力したいと思います。
マップは基本的に要素の順番が意味を持たないときに使い、要素の順番に意味がある場合はスライスを使うのがいいですが、今回はマップの値でソートしてキーを出力する方法を紹介します。
マップを値でソートしてキーを出力
下記がサンプルになります。マップを表す構造体を定義して、その構造体に対して sort の Interface を作成し、ソートして出力しています。
package main
import (
"fmt"
"sort"
)
// マップ用の構造体
type Pair struct {
Key string
Value int
}
type PairList []Pair
// ソート用のInterface
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] }
func printKeyOrderByValue(targetMap map[string]int) {
pl := make(PairList, len(targetMap))
i := 0
for k, v := range targetMap {
pl[i] = Pair{k, v}
i++
}
sort.Sort(pl)
// 逆順
//sort.Sort(sort.Reverse(pl))
for _, v := range pl {
fmt.Printf("%s: %d\n", v.Key, v.Value)
}
}
func main() {
targetMap := map[string]int{
"five": 5,
"nine": 9,
"three": 3,
"four": 4,
"six": 6,
"two": 2,
"ten": 10,
"seven": 7,
"one": 1,
"eight": 8,
}
printKeyOrderByValue(targetMap)
}