John Doe
John Doe

Reputation: 147

Groovy Custom Comparator

I try to figure out how build custom Comparator. I found a similar question but I'm still stuck. I want to sort files using a few ArrayLists, for example:

my Files:

 def files = ['author/foo.pkb', 'author/foo.pks', 
'version/test1.pks', 'version/test1.pkb', 'Somethink/foo.sql']

My order list:

def my_order = ['version', 'author', 'somethink'] // 1 value
def my_extension_order ['.pks', '.pkb']

And I want build somethink like that:

def my_index = { x ->
        return my_order.findIndexOf { x.contains(it) }
    }
def my_extension_order = { y ->
        return my_extension_order.findIndexOf { y.contains(it) }
    }

files.sort { a, b -> my_index(a) <=> my_index(b) ?: a <=> b && // sort files and extension

In output I want have sorted files by my_order and include my_extension_order. It should look like that:

def = ['version/test1.pks', 'version/test1.pkb', 'author/foo.pks', 'author/foo.pkb', 
'Somethink/foo.sql']

Summarizing in file.sort I want sort my files by 2 ArrayLists to get one consistent output. So how build a comparator to do that?

Upvotes: 1

Views: 2522

Answers (1)

Vampire
Vampire

Reputation: 38714

This will do:

def my_index = { x -> my_order.findIndexOf { x.contains(it) } }
def my_extension_index = { y -> my_extension_order.findIndexOf { y.contains(it) } }
files.sort { a, b -> my_index(a) <=> my_index(b) ?: (my_extension_index(a) <=> my_extension_index(b) ?: a <=> b) }

Upvotes: 3

Related Questions