This should do it:
// Define our input list def list = [ 'Armadillo', 'Cat', 'Dog', 'Cow', 'Zebra', 'Horse', 'Cow' ] // Define a closure that will do the sorting def sorter = { String a, String b, List prefixes=[ 'Cat', 'Cow' ] -> // Get the index into order for a and b // if not found, set to being Integer.MAX_VALUE def (aidx,bidx) = [a,b].collect { prefixes.indexOf it }.collect { it == -1 ? Integer.MAX_VALUE : it } // Compare the two indexes. // If they are the same, compare alphabetically aidx <=> bidx ?: a <=> b } // Create a new list by sorting using our closure def sorted = list.sort false, sorter // Print it out println sorted
What prints:
[Cat, Cow, Cow, Armadillo, Dog, Horse, Zebra]
I commented on this to try to explain every step that is required. Adding default prefix elements as an optional parameter in sorter
closure means that we can do things like this to change the default value:
// Use Dog, Zebra, Cow as our prefix items def dzc = list.sort false, sorter.rcurry( [ 'Dog', 'Zebra', 'Cow' ] ) println dzc
Which then prints a list sorted as:
[Dog, Zebra, Cow, Cow, Armadillo, Cat, Horse]