Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort with different number of digits in java?

Tags:

java

sorting

I created a list of files in a directory with f.listFiles().
Unfortunately they are very differently named like:
001.pdf
098.pdf
100.pdf
1000.pdf
now the array of files in the directory sets the 1000.pdf before the 100.pdf.
How can I sort this so that the files areback in the right order?

Thanks for help!

like image 204
bootsector Avatar asked Nov 23 '25 11:11

bootsector


1 Answers

You may prepend the names with spaces to the same length:

File[] files = f.listFiles();
if(files != null) {
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return String.format("%100s", o1.getName()).compareTo(
                   String.format("%100s", o2.getName()));
        }
    });
    System.out.println(Arrays.toString(files));
}

Or shorter if you are using Java-8:

File[] files = f.listFiles();
if(files != null) {
    Arrays.sort(files, Comparator.comparing(file -> String.format("%100s", file.getName())));
    System.out.println(Arrays.toString(files));
}
like image 178
Tagir Valeev Avatar answered Nov 25 '25 01:11

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!