Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy custom sort a map by value

Tags:

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 !

like image 974
Adrien Be Avatar asked Dec 03 '12 15:12

Adrien Be


People also ask

How do I sort a map in groovy?

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.

Does map sort by key or value?

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.


2 Answers

To sort with case insensitive, use

m.sort { it.value.toLowerCase() }
like image 50
doelleri Avatar answered Oct 20 '22 12:10

doelleri


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 }
like image 34
tim_yates Avatar answered Oct 20 '22 14:10

tim_yates