Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to sort lowercase before uppercase strings

Tags:

java

sorting

I want the files to be ordered by their abs path name, but I want the lowercase to be sorted before the uppercase. Example: Let's say I got 4 files:

files2.add("b");
files2.add("A");
files2.add("a");
files2.add("B");

the order with this code is: [A, B, a, b] I want it to be: [a, A, b, B]

import java.io.File;
import java.util.*;

public class Abs {

    public ArrayList<File> getOrder(ArrayList<File> files) {
        Collections.sort(files, new Comparator<File>() {
            public int compare(File file1, File file2) {
                return file1.getAbsolutePath().compareTo(file2.getAbsolutePath());
            }
        });
        return files;
    }

}
like image 699
Kuyo Avatar asked May 07 '13 16:05

Kuyo


1 Answers

You can probably use library or utility classes with this behaviour, or you can build your own comparator.

    new Comparator<File>() {
        public int compare(File file1, File file2) {
            // Case-insensitive check
            int comp = file1.getAbsolutePath().compareToIgnoreCase(file2.getAbsolutePath())
            // If case-insensitive different, no need to check case
            if(comp != 0) {
                return comp;
            }
            // Case-insensitive the same, check with case but inverse sign so upper-case comes after lower-case
            return (-file1.getAbsolutePath().compareTo(file2.getAbsolutePath()));
        }
    }
like image 72
dtech Avatar answered Oct 13 '22 01:10

dtech