Android:如何按最后一个文件夹名称对路径进行排序?

时间:2017-09-27 07:41:59

标签: android sorting arraylist collections compare

问题

如何按照上一个文件夹名称对路径进行排序?

我所知道的

我知道我可以这样对ArrayList进行排序:

    Collections.sort(aL_dirsWithPicsInside, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

输出:

/storage/5AA6-2B7E/Army
/storage/5AA6-2B7E/DCIM/Camera
/storage/5AA6-2B7E/DCIM/Canyoning
/storage/5AA6-2B7E/DCIM/Eigene Fotos/28.11.2015 - Arosa Eichhörnchenweg
/storage/5AA6-2B7E/Guns
/storage/emulated/0/DCIM/Friends
/storage/emulated/0/DCIM/Screenshots
/storage/emulated/0/DCIM/Südafrika

所以它对整个字符串进行排序。

我需要的是此输出(按最后一个文件夹名称排序):

/storage/5AA6-2B7E/DCIM/Eigene Fotos/28.11.2015 - Arosa Eichhörnchenweg
/storage/5AA6-2B7E/Army
/storage/5AA6-2B7E/DCIM/Camera
/storage/5AA6-2B7E/DCIM/Canyoning
/storage/emulated/0/DCIM/Friends
/storage/5AA6-2B7E/Guns
/storage/emulated/0/DCIM/Screenshots
/storage/emulated/0/DCIM/Südafrika

2 个答案:

答案 0 :(得分:2)

Collections.sort(aL_dirsWithPicsInside, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String[] segments1 = s1.split("/");
        String[] segments2 = s2.split("/");
        return segments1[segments1.length-1].compareToIgnoreCase(segments2[segments2.length-1]);
    }
});

此外,您应该控制该路径是正确的,并且它具有最后一部分。

答案 1 :(得分:0)

试试这个:

 Collections.sort(aL_dirsWithPicsInside, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            String str1 = s1.substring(s1.lastIndexOf("/")+1,s1.length());
            String str2 = s2.substring(s2.lastIndexOf("/")+1,s2.length());
            return str1.compareToIgnoreCase(str2);
        }
 });