Search code examples
javaandroidsortingfilesystemsandroid-file

Wrong order when Sort By Name is applied


I have some files in a folder stored in Android device.

Folder name = english/

File names = 001-001-0000.png, 001-001-000.png, 001-001-001.png, 001-001,002.png, 001-001-003.png ... upto 001-001-010.png

I have to load them on screen in sorted order by their name. I am using this code

String[] files = dir.list();
    Arrays.sort(files, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

The result I got is

001-001-000.png 001-001-0000.png 001-001-001.png 001-001,002.png 001-001-003.png ... 001-001-010.png

But when I check on explorer on my Windows PC I got

001-001-0000.png 001-001-000.png 001-001-001.png 001-001,002.png 001-001-003.png ... 001-001-010.png

The difference here is that the file which ends with four 0s (001-001-0000.png) comes before the file which ends with three 0s (001-001-000.png) and I need the same sorting order in my code.


Solution

  • Try this compare method:

    @Override
    public int compare(String o1, String o2) {
        String o1_prefix = o1.split(".")[0];
        String o2_prefix = o2.split(".")[0];
        if(o1_prefix.startsWith(o2_prefix)) 
            return -1;
        else if(o2_prefix.startsWith(o1_prefix)) 
            return 1;
        else return o1.compareToIgnoreCase(o2);
    }