golang map排序

//map排序

package mapsort

import (
    "sort"
)

type MapStore []Item

type Item struct {
    Key   string
    Value interface
}

func NewMapStore(m map[string]interface) MapStore {
    ms := make(MapStore, 0, len(m))
    for k, v := range m {
        ms = append(ms, Item{k, v})
    }
    return ms
}
func (ms MapStore) Len() int {
    return len(ms)
}
func (ms MapStore) Less(i, j int) bool {
    return ms[i].Key < ms[j].Key
}
func (ms MapStore) Swap(i, j int) {
    ms[i].Key, ms[j].Key = ms[j].Key, ms[i].Key
    ms[i].Value, ms[j].Value = ms[j].Value, ms[i].Value
}
func SortString(s []string) []string {
    sort.Strings(s)
    return s
}

func JudgeSortString(s []string) bool {
    return sort.StringsAreSorted(s)
}
map排序测试
package mapsort

import (
    "fmt"
    "sort"
    "testing"
)

func TestSortString(t *testing.T) {
    m := map[string]string{
        "daf":   "ewe",
        "wwer":  "qwew",
        "aqerq": "daw",
        "m":     "daw",
    }
    ms := NewMapStore(m)
    sort.Sort(ms)
    fmt.Println(ms)
    s1 := []string{"test", "test2", "new", "badd", "amodify"}
    fmt.Println(JudgeSortString(s1))
    ns := SortString(s1)
    fmt.Println(s1)
    fmt.Println(JudgeSortString(ns))
    fmt.Println(ns)

}