Sort a String ArrayList numerically in Android

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published