Search code examples
androidsortingcomparatorfilelist

Sort Filelist, Folders then Files, both alphabetically in Android


In my Android App I have a fileList and sort it with this:

Collections.sort(fileList, new ItemFileNameComparator());

To sort this list alphabetically I use the following code:

    private class ItemFileNameComparator implements Comparator<Item> {
    public int compare(Item lhs, Item rhs) {
    return lhs.file.toLowerCase(Locale.GERMAN).compareTo(rhs.file.toLowerCase(Locale.GERMAN));
    }
}

But this sorts all items alphabetically, I want to have folders first sorted alphabetically, then files sorted alphabetically. Is there a way to do this? Thank you for your help.


Solution

  • I think the variable file of Item is string. If so you have to change it to File as shown. If not you may not need converting string to file.

    private static class ItemFileNameComparator implements Comparator<Item> {
        public int compare(Item lhs, Item rhs) {
            File lhsFile = new File(lhs.file.toLowerCase(Locale.GERMAN));
            File rhsFile= new File( rhs.file.toLowerCase(Locale.GERMAN));
    
            String lhsDir = lhsFile.isDirectory()? lhsFile.getPath() : lhsFile.getParent();
            String rhsDir = rhsFile.isDirectory()? rhsFile.getPath() : rhsFile.getParent();
    
            int result =  lhsDir.toLowerCase().compareTo(rhsDir .toLowerCase());    
    
            if (result != 0) {
                return result;
            }else{              
                if(lhsFile.isDirectory()!= rhsFile.isDirectory()){
                    return lhsFile.getParent().toLowerCase().compareTo( rhsFile.getParent().toLowerCase());
                }
                return lhsFile.getName().toLowerCase().compareTo( rhsFile.getName().toLowerCase());
            }
        }