Java sort String array of file names by their extension

前端 未结 8 768
后悔当初
后悔当初 2021-01-13 02:29

I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?

8条回答
  •  再見小時候
    2021-01-13 02:48

    You can implement a custom Comparator of Strings. Make it sort them by the substring after the last index of '.'. Then pass in the comparator and your array into

    Arrays.sort(stringArray, yourComparator);
    
    //  An implementation of the compare method
    public int compare(String o1, String o2) {
        return o1.substring(o1.lastIndexOf('.')).compareTo(o2.substring(o2.lastIndexOf('.'));
    }
    

提交回复
热议问题