繁体   English   中英

目录和文件之间的Collections.sort

[英]Collections.sort between Directories and Files

我正在使用字符串Arraylist:ArrayList条目= new ArrayList(Arrays.asList(“”));

并动态地赋予价值。 它可能包含目录或文件的名称。

我需要在ListView中显示条目,这样,首先所有目录都按排序顺序显示,然后文件按排序顺序显示。

这可能吗? 如果是,有任何提示吗? 感谢帮助..我正在使用

Collections.sort(entries); 对我的条目进行排序。

将2参数版本与自定义比较器一起使用。 比较如下:

boolean firstFileIsDirectory = file1.isDirectory();
boolean secondFileIsDirectory = file2.isDirectory();
if(firstFileIsDirectory  && !secondFileIsDirectory){
    return -1;
}
if(!firstFileIsDirectory  && secondFileIsDirectory){
    return 1;
}
return String.compare(filename1, filename2);

我已经做了。 使用的逻辑:将条目分成两个ArrayList。 一个具有目录其他文件。 分别对这两个ArrayList进行排序。 最后将这两个添加到“条目”中。 这是代码:

private void sortEntries(String path){
    ArrayList<String> entriesDir = new ArrayList<String>(Arrays.asList(""));
    ArrayList<String> entriesFile = new ArrayList<String>(Arrays.asList(""));
    entriesDir.removeAll(entriesDir);
    entriesFile.removeAll(entriesFile);
    int fileCounter=0, dirCounter=0;
    path = path.equals("/") ? "" : path;
    for(int i=1;i<=entries.size();i++){
        if((new File(path+"/"+entries.get(i-1))).isFile()) entriesFile.add(fileCounter++, entries.get(i-1));
        else entriesDir.add(dirCounter++, entries.get(i-1));
    }
    Collections.sort(entriesDir,String.CASE_INSENSITIVE_ORDER);
    Collections.sort(entriesFile,String.CASE_INSENSITIVE_ORDER);
    entries.removeAll(entries);
    entries.addAll(entriesDir);
    entries.addAll(entriesFile);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM