Siva Siva - 1 year ago 111
Groovy Question

sort list of maps in grovvy

Hi I have a list of maps in groovy like

def v=[[val1:'FP'],[val1:'LP'],[val1:'MP'],[val1:'MP'],[val1:'LP'],[val1:'FP']]

I wanted to sort based on the following order FP,MP,LP

I tried doing

x.val1 <=> y.val1

which prints
[[val1:FP], [val1:FP], [val1:LP], [val1:LP], [val1:MP], [val1:MP]]
which is sorted alphabetically, but I need it to be sorted in the following format

Answer Source

Not really looking for points here, I just want to mention an alternative. Whenever I am dealing with a fixed, ordered list of strings I immediately think of using enums instead:

enum PValue { FP, MP, LP }

Now we have an ordered set of constants that readily converts to and from string values. So sorting looks as simple as this:

v.sort { x, y -> PValue[x.val1] <=> PValue[y.val1] }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download