Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java列表按名称排序(整数)_Java_List_Sorting - Fatal编程技术网

Java列表按名称排序(整数)

Java列表按名称排序(整数),java,list,sorting,Java,List,Sorting,我有一个名为0.jpg、1.jpg等的文件名列表。。我想以降序的方式来订购,但似乎我在这方面遇到了麻烦。我还注意到升序与我想的不太一样,下面是一个例子: file 1.jpg file 10.jpg file 100.jpg file 101.jpg ... file 109.jpg file 11.jpg 所以我的问题是,我怎样才能正确地进行降序呢? 以下是我现在正在做的事情: Collections.sort(files, new Comparator<File>() {

我有一个名为
0.jpg、1.jpg
等的文件名列表。。我想以降序的方式来订购,但似乎我在这方面遇到了麻烦。我还注意到升序与我想的不太一样,下面是一个例子:

file 1.jpg
file 10.jpg
file 100.jpg
file 101.jpg
...
file 109.jpg
file 11.jpg
所以我的问题是,我怎样才能正确地进行降序呢? 以下是我现在正在做的事情:

Collections.sort(files, new Comparator<File>() {
                @Override
                public int compare(File s1, File s2) {
                    return s1.getName().compareToIgnoreCase(s2.getName());
                }
            });
Collections.sort(文件、新比较器(){
@凌驾
公共整数比较(文件s1、文件s2){
返回s1.getName().compareToIgnoreCase(s2.getName());
}
});
尝试(仅当文件具有相同的名称模式时有效,即:
'file xxx.jpg'

Collections.sort(文件、新比较器(){
@凌驾
公共整数比较(文件s1、文件s2){
int f1=Integer.parseInt(s1.getName().replace(“文件”),replace(“.jpg”),replace;
int f2=Integer.parseInt(s2.getName().replace(“文件”),replace(“.jpg”),replace;
返回f1>f2-1:(f1==f2?0:1);
}
});

File.getName()
显然返回一个
字符串,因此这种顺序(1、10、100)是预期的。您需要从字符串中提取数字部分(例如,使用正则表达式),如果存在整数,则解析整数(例如,如果捕获的子字符串长度大于零),然后比较整数。

您应该在调用该方法之前解析文件名 试试这个:

Arrays.sort(fileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
    try {
        int i = Integer.parseInt(file1.getName());
        int j = Integer.parseInt(file2.getName());
        return i - j;
    } catch(NumberFormatException e) {
        throw new AssertionError(e);
    }
} });
Arrays.sort(fileArray,newcomparator(){
公共int比较(文件file1、文件file2){
试一试{
int i=Integer.parseInt(file1.getName());
intj=Integer.parseInt(file2.getName());
返回i-j;
}捕获(数字格式){
抛出新断言错误(e);
}
} });

和@user370305您的回答引导我找到了答案,请提交您的答案,以便我可以接受。答案无需额外说明。:)快乐编码…:)我想这应该行得通,但答案在@user370305的评论中,谢谢!
Arrays.sort(fileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
    try {
        int i = Integer.parseInt(file1.getName());
        int j = Integer.parseInt(file2.getName());
        return i - j;
    } catch(NumberFormatException e) {
        throw new AssertionError(e);
    }
} });