groovy中map自定义比较器的创建
我在groovy上过课groovy中map自定义比较器的创建,groovy,Groovy,我在groovy上过课 class WhsDBFile { String name String path String svnUrl String lastRevision String lastMessage String lastAuthor } 和映射对象 def installFiles = [:] 这个循环由 WhsDBFile dbFile = new WhsDBFile() installFiles[svnDiffStatus.
class WhsDBFile {
String name
String path
String svnUrl
String lastRevision
String lastMessage
String lastAuthor
}
和映射对象
def installFiles = [:]
这个循环由
WhsDBFile dbFile = new WhsDBFile()
installFiles[svnDiffStatus.getPath()] = dbFile
现在,我尝试使用自定义比较器对其进行排序
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
@Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return 1
} else if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
您可以尝试对entrySet()进行排序:
sort
还可以将闭包作为参数,强制使用比较器的compare()
方法,如下所示。使用toUpper()
方法只是模仿FilenameUtils.getBaseName()的实现
installFiles.sort{a,b->
toUpper(a.value.name)toUpper(b.value.name)
}
//正在复制FilenameUtils.getBaseName()的实现
//这可以根据需要定制
串头(串a){
a、 toUpperCase()
}
添加了可运行示例的可能性。这是我的gradle脚本的一部分。你为什么要用映射来保持秩序?@christopher我将使用映射数据类型按文件名查找WhsDBFile对象。然后你应该将该键设置为一些值,以便用于查找WhsDBFile
对象。它不应该用于搜索。这就破坏了地图的意义。
project.task('sample') << {
def installFiles = [:]
WhsDBFile dbFile = new WhsDBFile()
installFiles['sample_path'] = dbFile
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
@Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (o1.name > o2.name) {
return 1
} else if (o1.name > o2.name) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
}
def sortedEntries = installFiles.entrySet().sort { entry1, entry2 ->
entry1.value <=> entry2.value
}
def sortedMap = installFiles.entrySet().sort { entry1, entry2 ->
...
}.collectEntries()
installFiles.sort { a, b ->
toUpper(a.value.name) <=> toUpper(b.value.name)
}
// Replicating implementation of FilenameUtils.getBaseName()
// This can be customized according to requirement
String toUpper(String a) {
a.toUpperCase()
}