Issue
I have an ArrayList of Files with names:
{"Chapter 1", "Chapter 2", "Chapter 3"...}
This can go on till the hundreds maybe thousands. Basically, I want to know how to sort the ArrayList so that I don't get:
{"Chapter 1", "Chapter 10", "Chapter 11"...}
Because when I use this code:
if (files != null && files.size() > 1) {
files.sort(Comparator.comparing(file -> file.getName().toLowerCase(Locale.ROOT)));
}
That's what it does...
Solution
You can use split if the naming of your files is consistent
files.sort(Comparator.comparingInt(
file -> Integer.parseInt(file.getName().split("\\s+")[1])));
or remove non-digit characters using replaceAll
files.sort(Comparator.comparingInt(
file -> Integer.parseInt(file.getName().replaceAll("\\D+",""))));
Answered By - Eritrean
Answer Checked By - David Marino (JavaFixing Volunteer)