Reputation: 20041
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 !
Upvotes: 22
Views: 34823
Reputation: 866
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.
Upvotes: 8
Reputation: 169
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]
Upvotes: 5
Reputation: 19682
To sort with case insensitive, use
m.sort { it.value.toLowerCase() }
Upvotes: 47
Reputation: 171084
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 }
Upvotes: 13