arrays - Custom Sort Groovy JSONArray - Custom Values First, Then Alphabetical -


i have static list of values in jsonarray. here example array:

jsonarray json = new jsonarray()  json = ["b", "e", "c", "z", "a", "x", "f", "h"] 

i need sort json array in custom way. need put "e" first, "f" second, , sort rest alphabetical order.

i want end result this:

json = ["e", "f", "a", "b", "c", "h", x", "z"] 

groovy has basic sort functionality can sort alphabetically or reverse alphabetically using:

json.sort() 

or

json.reverse() 

i'm looking easy way custom sort.

you can use closures if define own sort method, you're asking array splitting little normal sorting.

json.findall{it = 'e'} + json.findall{it = 'f'} + json.findall{!(it in ['e', 'f'])}.sort() 

if you're worried efficiency of looping through json 3 times can iterate through json once, adding different arrays go.

the below example little fancier. inject method iterate on collection, passing value between each iteration (in our case list of 3 lists. first list hold our e's, second our f's, , 3rd else. after sorting our catchall list use .flatten() transform 3 lists 1 list.

list organizedlist = json.inject([[],[],[]]) {list<list> result, string jsonvalue ->     select(jsonvalue) {         case 'e':             result.get(0).add(jsonvalue) // have added 'e' symmetry             break;         case 'f':             result.get(1).add(jsonvalue)             break;         default:             result.get(2).add(jsonvalue)     }     return result // gets passed each iteration on json } organizedlist.get(2).sort() // sort on list modifies original list  organizedlist.flatten() 

it's possible using sort closure define own sorting; can see, doesn't flow quite easily.

json.sort {string a, string b ->       if (a = b) return 0 // efficiency's sake      def letterfirst = {string priority -> // closure sort against hardcoded value         if (a = priority) return 1         if (b = priority) return -1             return 0     }      def toreturn = letterfirst('e')     if (!toreturn) toreturn = letterfirst('f') // groovy evaluates 0 false     if (!toreturn) toreturn = <=> b     return toreturn  } 

Comments