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.
Collections.sort(); lets you pass a custom comparator for ordering. For case insensitive ordering String class provides a static final comparator called CASE_INSENSITIVE_ORDER.
So in your case all that's needed is:
Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);
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()));
}
}
Check the Collator class.
You'll have to read carefully what those constants mean, but one of them should make it possible for you to put lowercase letters before the upper-case letters.
Try this simple implementation :
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("A");
list.add("B");
System.out.println(list);
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.toLowerCase().equals(o2.toLowerCase())) {
if (o1.toLowerCase().equals(o1)) {
return -1;
} else {
return 1;
}
} else {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
}
});
System.out.println(list);
}
As suggested by others, Collator
does what you want. Writing one of those collator rules looked a bit scary, but it looks like the standard English Collator
does exactly what you want:
public static void main(String... args)
{
List<String> items = Arrays.asList("b", "A", "a", "B");
Collections.sort(items, Collator.getInstance(Locale.ENGLISH));
System.out.println(items);
}
gives:
[a, A, b, B]
You could implement your own Comparator
, which in turn uses a Collator
. See example.