• 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)
    }

      

  • 相关阅读:
    spring core与context的理解
    maven项目中pom.xml快速生成
    MariaDB常用命令
    MariaDB快速入门指南
    My_plan_51
    Oracle简介及安装
    Oracle单行函数
    oracle多表查询
    单点登录原理与简单实现
    JavaScript 的时间消耗
  • 原文地址:https://www.cnblogs.com/zipon/p/12901071.html
Copyright © 2020-2023  润新知