StringList : sort by custom algorithm

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()) ;
	}
});
1 Like

(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);
}
//

1 Like

forum.Processing.org/two/discussions/tagged%3FTag=lastmodified().html

Hello
Special thanks to @Chrisir @mnse
Have a good day

1 Like