Groovy custom sort a map by value

…衆ロ難τιáo~ 提交于 2020-01-01 04:13:09

问题


I have a map such as

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

I want to sort this map by its value but ignoring the case (this is really why the custom sort is needed). Hence I figured I had to implement a custom sort using a closure. But I'm brand new at Groovy and been struggling to get this very simple task done!

The desired results would be:

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

Thanks !


回答1:


To sort with case insensitive, use

m.sort { it.value.toLowerCase() }



回答2:


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 }



回答3:


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]



回答4:


If somebody is looking for how to make in 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.



来源:https://stackoverflow.com/questions/13686659/groovy-custom-sort-a-map-by-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!