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
That prints:
[Cat, Cow, Cow, Armadillo, Dog, Horse, Zebra]
I've commented it to try and explain each step it takes. By adding the default prefix items as an optional parameter on the sorter
closure, it means we can do stuff like this to change the default:
// Use Dog, Zebra, Cow as our prefix items
def dzc = list.sort false, sorter.rcurry( [ 'Dog', 'Zebra', 'Cow' ] )
println dzc
Which then prints the list sorted as:
[Dog, Zebra, Cow, Cow, Armadillo, Cat, Horse]