Groovy custom sort a map by value

后端 未结 4 783
说谎
说谎 2020-12-31 02:52

I have a map such as

m=[
     \"james\":\"silly boy\",
     \"janny\":\"Crazy girl\",
     \"jimmy\":\"funny man\",
     \"georges\":\"massive fella\"
];


        
相关标签:
4条回答
  • 2020-12-31 03:10

    BTW, here is code which is showing different sorting with and without toLowerCase():

    Map m =[ james  :"silly boy",
             janny  :"crazy girl",
             jimmy  :"Funny man",
             georges:"massive fella" ]
    Map sorted = m.sort { a, b -> a.value <=> b.value }
    println sorted
    sorted = m.sort { a, b -> a.value.toLowerCase() <=> b.value.toLowerCase() }
    println sorted
    

    And wll print:

    [jimmy:Funny man, janny:crazy girl, georges:massive fella, james:silly boy]
    [janny:crazy girl, jimmy:Funny man, georges:massive fella, james:silly boy]
    
    0 讨论(0)
  • 2020-12-31 03:25

    To sort with case insensitive, use

    m.sort { it.value.toLowerCase() }
    
    0 讨论(0)
  • 2020-12-31 03:35

    If somebody is looking for how to make it work in the Jenkins pipeline script, you will have to create a separate method with @NonCPS annotation for that:

    @NonCPS
    def getSorted(def mapSizeMap){
        mapSizeMap.sort(){ a, b -> b.value <=> a.value }
    }
    

    And then call it from the pipeline script.

    def sortedMapZoneMap = getSorted(mapZonesMap)

    You can of course apply "case sensitive" logic on top.

    0 讨论(0)
  • 2020-12-31 03:36

    Assuming you mean you want to sort on value, you can just do:

    Map m =[ james  :"silly boy",
             janny  :"Crazy girl",
             jimmy  :"funny man",
             georges:"massive fella" ]
    
    Map sorted = m.sort { a, b -> a.value <=> b.value }
    
    0 讨论(0)
提交回复
热议问题