Hello
In my sketch, a StringList stores some paths to files.
I want to sort this StringList not by alphabetical order, but by file modification date.
Is there a way to implement a custom sort algorithm ?
Thanks.
Hello
In my sketch, a StringList stores some paths to files.
I want to sort this StringList not by alphabetical order, but by file modification date.
Is there a way to implement a custom sort algorithm ?
Thanks.
Hi,
It depends on what you want to do, but for the first I would switch from StringList to ArrayList<String>
or better as you know that there are existing Files ArrayList<File>
.
Afterwards for the latter:
arrayListWithFileObjects.sort((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
Or if you want to keep Strings (If it is certain that the files exist) you can do s.th. like.
arrayListWithStrings.sort((s1,s2) -> Long.compare(new File(s1).lastModified(), new File(s2).lastModified()));
for the ArrayList<String>
version it would be better to go via stream and filter by existence and afterwards do the sort.
Cheers
— mnse
PS: The solution above is for Processing (>=4) with java8 support. For older Versions you can use s.th. like:
arrayListWithFileObjects.sort(new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(),f2.lastModified()) ;
}
});
(I can’t run it, old version of processing here)
// Files
ArrayList<File> arrayListWithFileObjects = new ArrayList();
String[] filenames;
//-------------------------------------------------------------------------------------------
void setup () {
size (1230, 700);
java.io.File folder = new java.io.File(dataPath(""));
filenames = folder.list();
printArray(filenames);
for (String s1 : filenames) {
arrayListWithFileObjects.add(new File(s1));
}
println("");
arrayListWithFileObjects.sort((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
// arrayListWithStrings.sort((s1, s2) -> Long.compare(new File(s1).lastModified(), new File(s2).lastModified()));
for (File f1 : arrayListWithFileObjects) {
println(f1.getPath());
}
//
}//func
void draw () {
background(0);
}
//