I have code to sort paths by date modified. I also want to write code to sort the paths in reverse order, and later I might want to add some other sorting methods. Is there a way to do all sortings from one class file? Or I need to create another class PathSortByDateReverse, PathSortByCreated, PathSortByFoo, etc. Also, how would I use different sorting methods?
import java.nio.file.Path;
import java.util.Comparator;
public class PathSortByDate implements Comparator<Path> {
@Override
public int compare(Path first, Path second) {
long seconddate = second.toFile().lastModified();
long firstdate = first.toFile().lastModified();
if (firstdate == seconddate) {
return 0;
} else if (firstdate > seconddate) {
return 1;
} else {
return -1;
}
}
}
Then I call it from another class:
public static ArrayList<Path> sortArrayListByDate(ArrayList<Path> pathlist) {
Collections.sort(pathlist,new PathSortByDate());
return pathlist;
}
source
share