由ArrayList对Groovy排序字符串

时间:2017-10-03 06:36:36

标签: sorting groovy

我尝试从我的ArrayList按顺序排序字符串。我有点困惑如何做到这一点。例如,我有我的订单清单:

def my_order = ['Version', 'Author', 'Somethink']
def files_sort = pack.files // here have string's to files

files_sort中包含db/author/test.sqldb/Somethink/test1.sql等随机字符串以及其他字符串。 我认为最简单的方法是使用循环遍历我的文件并使用基于我的order_list的排序?例如:

files.sort.each {
   it.sort(here give my_order ??)
}

感谢您的提示!

编辑:

输入列表:

def files_to_sort = ['db/author/test1.sql', 'db/author/foo.sql', 'db/version/test1.sql', 'db/Somethink/foo.sql']

my_order列表排序的输出列表:

def files_after_sort = ['db/version/test1.sql', 'db/author/test1.sql', 'db/author/foo.sql', 'db/Somethink/foo.sql']

2 个答案:

答案 0 :(得分:1)

def files = ['db/author/test1.sql', 'db/author/foo.sql', 'db/version/test1.sql', 'db/Somethink/foo.sql']
//convert array to uppercase values to support ignore-case
def my_order = ['Version', 'Author', 'Somethink'].collect{it.toUpperCase()} 

//closure to calculate sorting index of string `x` 
def my_index = {x->
    x = x.toUpperCase()
    return my_order.findIndexOf{ x.contains(it) }
}
//the compare in sort: first - by index, if index is same then by value itself
files.sort{a,b->  my_index(a)<=>my_index(b) ?: a<=>b }
println files

答案 1 :(得分:0)

因此,要获得排序数组,我循环遍历my_order并再次循环遍历文件。

my_order.each{ type ->
        files.sort.each{ file ->
            if(file =~ /.*$type.*/){
                println file
            }
        }
}