I have a file list which I want to sort and extract the top 3 last modified.
Constraint: I cannot use Java 7 due to compatibility issues on downstream apps
My current options
Solution 1
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
} });
Solution 2
public static void sortFilesDesc(File[] files) {
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if ((File)o1).lastModified().compareTo((File)o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
}
Problem
The above two solution takes more time to execute & memory. My file list consists of some 300 tar files with 200MB size each. so it is consuming more time & memory.
Is there is any way to efficiently handle this?
Every compare operation uses a file object which is of high memory is there is any way to release the memory and handle this effectively?
You can do it much faster.
Arrays.sort(…) uses “quick sort”, which takes ~ n * ln(n) operations.
This example takes only one iteration trough the whole array, which is ~ n operations.
On small numbers of files you won’t see much difference, but even for tens of files the difference will be significant, for bigger numbers – dramatic.
The code to check the algorithm (please put in a correct files structure):