golang map的排序

老是掉进golang数据结构map的坑里,PHP习惯了只有数组一种结构,老是会把map想成PHP不是默认key的数组,其实最大的不同就是map是随机排序的,以后用map的时候要提醒自己是不是有排序需求

golang map按key排序

//golang的map不保证有序性,所以按key排序需要取出key,对key排序,再遍历输出value
package main

import (
    "fmt"
    "sort"
)

func main() {
    // To create a map as input
    m := make(map[int]string)
    m[1] = "a"
    m[2] = "c"
    m[0] = "b"

    // To store the keys in slice in sorted order
    var keys []int
    for k := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)

    // To perform the opertion you want
    for _, k := range keys {
        fmt.Println("Key:", k, "Value:", m[k])
    }
}

golang map按value排序

//要对golang map按照value进行排序,思路是直接不用map,用struct存放key和value,实现sort接口,就可以调用sort.Sort进行排序了。
// A data structure to hold a key/value pair.
type Pair struct {
    Key   string
    Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }

// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
    p := make(PairList, len(m))
    i := 0
    for k, v := range m {
        p[i] = Pair{k, v}
        i ++
    }
    sort.Sort(p)
    return p
}

golang map递增排序

//sort.Sort是递增排序,如果要实现递减排序,用sort.Reverse
package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{4,3,2,1,5,9,8,7,6}
    sort.Sort(sort.Reverse(sort.IntSlice(a)))
    fmt.Println("After reversed: ", a)
}

golang map 排序的稳定性

//sort不保证排序的稳定性(两个相同的值,排序之后相对位置不变),排序的稳定性由sort.Stable来保证。
package main

import (
    "fmt"
    "sort"
)

type person struct {
  Name string
  Age int
}

type personSlice []person

func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }

func main() {
    a := personSlice {
      {
        Name: "AAA",
        Age: 55,
      },
      {
        Name: "BBB",
        Age: 22,
      },
      {
        Name: "CCC",
        Age: 0,
      },
      {
        Name: "DDD",
        Age: 22,
      },
      {
        Name: "EEE",
        Age: 11,
      },  
    }
    sort.Stable(a)
    fmt.Println(a)
}