Java how to sort lowercase before uppercase strings

前端 未结 6 959
南旧
南旧 2021-01-11 15:56

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.         


        
6条回答
  •  一生所求
    2021-01-11 16:15

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

        new Comparator() {
            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()));
            }
        }
    

提交回复
热议问题