sorting - 如何按自定义顺序对列表排序?

标签 sorting grails groovy

我想使用Groovy按定义的顺序对以下列表进行排序

def ls = [ 'sperson_firstname', 'a_id', 'a_name', 'scontact_street', 'scontact_email',  'sperson_nationality', 'scontact_tel', 'sperson _birthday', 'sperson_lastname', 'scontact_fax']

排序后应该这样排序:
 ls = ['a_id', 'a_name', 'sperson_firstname', 'sperson_lastname', 'sperson _birthday','sperson_nationality','scontact_street', 'scontact_email',  'scontact_tel', 'scontact_fax']

这意味着我定义的顺序应该先排序前缀
[a , sperson, scontact]

然后,对于每个前缀,应按定义的顺序对后缀进行排序

例如前缀的人应该排序为
['sperson_firstname', 'sperson_lastname', 'sperson _birthday','sperson_nationality']

对于前缀,联系人应该排序为
['scontact_street', 'scontact_email',  'scontact_tel', 'scontact_fax']

我努力了
def sortOrder = ["a","sperson","scontact"]
ls.sort{ls -> sortOrder.indexOf(ls.split("_")[0]) }

但这只能解决前缀排序...

最佳答案

您可以执行自己的操作并将其扩展为前缀:

List prefixOrder = ['a' , 'sperson', 'scontact']
Map suffixOrdersByPrefix = [
    a: [...],
    b: [...],
    c: [...]
]
def indexOfComparator = { list, a, b -> 
   list.indexOf(a).compareTo(list.indexOf(b)) 
}
def prefixComparator = { a, b -> 
   indexOfComparator(prefixOrder, a, b)
}
def suffixComparator = { prefix, a, b ->
   indexOfComparator(suffixOrdersByPrefix[prefix], a, b)
}

l.sort { a, b ->
    List<String> aTokens = a.tokenize('_'),
        bTokens = b.tokenize('_')
    prefixComparator(aTokens.first(), bTokens.first()) ?:
        suffixComparator(aTokens.first(), aTokens.last(), bTokens.last())
}

您比较前缀,如果相等(即比较返回0),则比较后缀。您可以使用...映射每个后缀的顺序,嗯,一个映射:)。

关于sorting - 如何按自定义顺序对列表排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742269/

相关文章:

java - 正确的归并排序实现?

PHP 使用 uasort 对数组进行排序

hibernate - 将Hibernate/Grails域对象保留在 session 中

在 View 上访问时,传递给 View 的 Grails Controller 数据为空?

git - Jenkins 管道构建 github pull 请求

eclipse - Eclipse-使用Spock和Groovy的新Gradle项目

arrays - 将元素保存在Map/Array/Collection中……Grails

java - 具有可比性的双链表排序

algorithm - 1元堆排序?

Grails无法安装插件