Java sort String array of file names by their extension

前端 未结 8 767
后悔当初
后悔当初 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:55

    If you just want to group the files by their extension and do not care about the actual alphabetical order, you can use this:

    I think the simplest thing you can do that also works when the filenname does not have a "." is to just reverse the names and compare them.

    Arrays.sort(ary, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String r1 = new StringBuffer(o1).reverse().toString();
            String r2 = new StringBuffer(o2).reverse().toString();
            return r1.compareTo(r2);
        }
    });
    

    Its a shame that java's string does not even have a reverse().

    0 讨论(0)
  • 2021-01-13 02:58

    Create your own Comparator that treats the strings as filenames and compares them based on the extensions. Then use Arrays.sort with the Comparator argument.

    0 讨论(0)
提交回复
热议问题