I have a list of files that I am trying to sort in the order of the most recent modified date to the least recent. The date is stored as a long value (milli seconds since the epoch) and I used Collections.sort to sort the files. I want the files to go from most recent to least recent (top to bottom), so I did R2-R1 instead of R1-R2 in the Comparator. The code I used is shown below:
Collections.sort(temp, new Comparator<RecordingFile>() {
@Override
public int compare(RecordingFile R1, RecordingFile R2) {
int x = (int) (R2.getLastModfied()-R1.getLastModfied());
return Integer.compare(x, 0);
}
});
This code resulted in something like so:
14-04-2022
10-04-2022
06-04-2022
05-04-2022
20-03-2022
...
18-04-2022
18-04-2022
17-04-2022
The list is somehow ordered correctly but incorrectly at the same time. The files are ordered in parts instead of fully. I tried shuffling the list before ordering and it resulted in a different order but still the same behaviour (ordered but in parts). To solve this, I did R1-R2 in the comparator and then reverse the sorted list. This resulted in a fully ordered list that takes into account all items in the list.
I was wondering if anyone knows why this happened?
CodePudding user response:
Just like in the comments, try using Comparator.comparing(RecordingFile::getLastModfied).reversed()
instead of doing it manually.
If you decide to still do it manually, check the lastModfied
type because if it's a long
then you shouldn't be returning the final result of the comparison as int