可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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; } }
回答1:
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.
回答2:
You could implement your own Comparator
, which in turn uses a Collator
. See example.
回答3:
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())); } }
回答4:
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]
回答5:
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); }