首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java排序按扩展名排列的文件名字符串数组

Java排序按扩展名排列的文件名字符串数组
EN

Stack Overflow用户
提问于 2009-01-13 19:32:21
回答 7查看 16K关注 0票数 5

我有一个文件名数组,需要根据文件名的扩展名对该数组进行排序。有什么简单的方法可以做到这一点吗?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-01-13 19:39:17

代码语言:javascript
复制
Arrays.sort(filenames, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // the +1 is to avoid including the '.' in the extension and to avoid exceptions
        // EDIT:
        // We first need to make sure that either both files or neither file
        // has an extension (otherwise we'll end up comparing the extension of one
        // to the start of the other, or else throwing an exception)
        final int s1Dot = s1.lastIndexOf('.');
        final int s2Dot = s2.lastIndexOf('.');
        if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
            s1 = s1.substring(s1Dot + 1);
            s2 = s2.substring(s2Dot + 1);
            return s1.compareTo(s2);
        } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
            return -1;
        } else { // only s1 has an extension, so s1 goes second
            return 1;
        }
    }
});

完整性方面:java.util.Arraysjava.util.Comparator

票数 21
EN

Stack Overflow用户

发布于 2009-01-13 19:35:07

如果我没记错,Arrays.sort(...)获取将用于进行排序的Comparator<>。您可以提供它的一个实现来查看字符串的扩展部分。

票数 4
EN

Stack Overflow用户

发布于 2009-01-13 19:35:27

您可以实现字符串的自定义Comparator。使其按照'.'的最后一个索引之后的子字符串对它们进行排序。然后将比较器和数组传入

代码语言:javascript
复制
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('.'));
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/440430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档