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 !
Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.
To sort with case insensitive, use
m.sort { it.value.toLowerCase() }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With