Creation of custom comparator for map in groovy -
i have class in groovy
class whsdbfile { string name string path string svnurl string lastrevision string lastmessage string lastauthor }
and map object
def installfiles = [:]
that filled in loop by
whsdbfile dbfile = new whsdbfile() installfiles[svndiffstatus.getpath()] = dbfile
now try sort custom comparator
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);
but error java.lang.string cannot cast whsdbfile
any idea how fix this? need use custom comparator, cause more complex in future.
p.s. full source of sample gradle task (description of whsdbfile class above):
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); }
you can try sort entryset() :
def sortedentries = installfiles.entryset().sort { entry1, entry2 -> entry1.value <=> entry2.value }
you have collection of map.entry invocation. in order have map, can collectentries() result :
def sortedmap = installfiles.entryset().sort { entry1, entry2 -> ... }.collectentries()
Comments
Post a Comment