zoukankan      html  css  js  c++  java
  • golang map数组根据某个字段值排序

    package main

    import (
    "fmt"
    "math/rand"
    "sort"
    "strconv"
    "zentaotimer/libs/github.com/wonderivan/logger"
    )

    type MapsSort struct {
    Key string
    MapList []map[string] interface{}
    }

    func (m *MapsSort) Len() int {
    return len(m.MapList)
    }

    func (m *MapsSort) Less(i, j int) bool {
    var ivalue float64
    var jvalue float64
    var err error
    fmt.Println(m.Key)
    switch m.MapList[i][m.Key].(type) {
    case string:
    ivalue,err = strconv.ParseFloat(m.MapList[i][m.Key].(string),64)
    if err != nil {
    logger.Error("map数组排序string转float失败:%v",err)
    return true
    }
    case int:
    ivalue = float64(m.MapList[i][m.Key].(int))
    case float64:
    ivalue = m.MapList[i][m.Key].(float64)
    case int64:
    ivalue = float64(m.MapList[i][m.Key].(int64))
    }
    switch m.MapList[j][m.Key].(type) {
    case string:
    jvalue,err = strconv.ParseFloat(m.MapList[j][m.Key].(string),64)
    if err != nil {
    logger.Error("map数组排序string转float失败:%v",err)
    return true
    }
    case int:
    jvalue = float64(m.MapList[j][m.Key].(int))
    case float64:
    jvalue = m.MapList[j][m.Key].(float64)
    case int64:
    jvalue = float64(m.MapList[j][m.Key].(int64))
    }
    return ivalue > jvalue
    }

    func (m *MapsSort) Swap(i, j int) {
    m.MapList[i],m.MapList[j] = m.MapList[j],m.MapList[i]
    }

    func main() {
    mapsSort := MapsSort{}
    mapsSort.Key = "data"
    maps:= make([]map[string] interface{},0)
    for i:=0 ; i<10;i++ {
    data := rand.Float64()
    mapTemp := make(map[string] interface{})
    mapTemp["data"] = data
    mapTemp["aaa"] = fmt.Sprintf("aaa%d",i)
    maps = append(maps, mapTemp)
    }

    mapTemp := make(map[string] interface{})
    mapTemp["data"] = "1.001"
    mapTemp["aaa"] = fmt.Sprintf("aaa")
    maps = append(maps, mapTemp)
    fmt.Println(maps)
    mapsSort.MapList = maps
    fmt.Println(mapsSort)
    sort.Sort(&mapsSort)
    fmt.Println(mapsSort)
    }

      

  • 相关阅读:
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    449. Serialize and Deserialize BST
    114. Flatten Binary Tree to Linked List
    199. Binary Tree Right Side View
    173. Binary Search Tree Iterator
    98. Validate Binary Search Tree
    965. Univalued Binary Tree
    589. N-ary Tree Preorder Traversal
    eclipse设置总结
  • 原文地址:https://www.cnblogs.com/zipon/p/12901071.html
Copyright © 2011-2022 走看看