简体   繁体   English

目录和文件之间的Collections.sort

[英]Collections.sort between Directories and Files

I am using Arraylist of strings: ArrayList entries = new ArrayList(Arrays.asList("")); 我正在使用字符串Arraylist:ArrayList条目= new ArrayList(Arrays.asList(“”));

and giving values dynamically. 并动态地赋予价值。 It may contain the names of Directories or Files. 它可能包含目录或文件的名称。

I need to show entries in ListView such that, first all directories are shown in sort order then files in sort order. 我需要在ListView中显示条目,这样,首先所有目录都按排序顺序显示,然后文件按排序顺序显示。

Is this possible? 这可能吗? if yes, any hint? 如果是,有任何提示吗? Appreciate the help.. I am using 感谢帮助..我正在使用

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

Use the 2 parameter version with a custom comparator. 将2参数版本与自定义比较器一起使用。 Compare it such that: 比较如下:

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

I have done it. 我已经做了。 Logic used: separate the entries into two ArrayList. 使用的逻辑:将条目分成两个ArrayList。 One having directories other files. 一个具有目录其他文件。 Sort these two ArrayLists separately. 分别对这两个ArrayList进行排序。 Finally add these two to "entries". 最后将这两个添加到“条目”中。 Here is the code: 这是代码:

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