I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list ba
A slightly more modernized version of the answer of @jason-orendorf.
Note: this implementation keeps the original array untouched, and returns a new array. This might or might not be desirable.
files = Arrays.stream(files)
.map(FileWithLastModified::ofFile)
.sorted(comparingLong(FileWithLastModified::lastModified))
.map(FileWithLastModified::file)
.toArray(File[]::new);
private static class FileWithLastModified {
private final File file;
private final long lastModified;
private FileWithLastModified(File file, long lastModified) {
this.file = file;
this.lastModified = lastModified;
}
public static FileWithLastModified ofFile(File file) {
return new FileWithLastModified(file, file.lastModified());
}
public File file() {
return file;
}
public long lastModified() {
return lastModified;
}
}
But again, all credits to @jason-orendorf for the idea!