-1

I have a list of file names that are named like 0.jpg,1.jpg etc.. and I want to order them in descending fashion but seems that I'm having trouble doing that. Also I've noticed that the ascending ordering is not quite like I want to, here is an example:

file 1.jpg
file 10.jpg
file 100.jpg
file 101.jpg
...
file 109.jpg
file 11.jpg

So my question is how can I do a descending ordering but correctly? Here is what im I doing right now:

Collections.sort(files, new Comparator<File>() {
                @Override
                public int compare(File s1, File s2) {
                    return s1.getName().compareToIgnoreCase(s2.getName());
                }
            });
2Dee
  • 8,609
  • 7
  • 42
  • 53
Darko Petkovski
  • 3,892
  • 13
  • 53
  • 117

3 Answers3

2

Try (only works if the files had the same name pattern ie: 'file xxx.jpg')

Collections.sort(files, new Comparator<File>() {
                @Override
                public int compare(File s1, File s2) {
                    int f1 = Integer.parseInt(s1.getName().replace("file ", "").replace(".jpg",""));
                    int f2 = Integer.parseInt(s2.getName().replace("file ", "").replace(".jpg",""));
                    return f1 > f2?-1:(f1==f2?0:1);
                }
            });
Marcx
  • 6,806
  • 5
  • 46
  • 69
0

File.getName() returns a String, obviously, so this ordering (1, then 10, then 100) is expected. You need to extract the numerical part from the string (e.g. using a regular expression), parse the integer if it's there (e.g. if the captured substring length is greater than zero) and compare the integers.

biggvsdiccvs
  • 299
  • 3
  • 12
0

You should parse the name of the files before calling the method Try this :

Arrays.sort(fileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
    try {
        int i = Integer.parseInt(file1.getName());
        int j = Integer.parseInt(file2.getName());
        return i - j;
    } catch(NumberFormatException e) {
        throw new AssertionError(e);
    }
} });
Mel
  • 453
  • 1
  • 4
  • 14