How to sort List<File> to list directories first and grouping files by directory?

十年热恋 提交于 2019-12-05 03:00:28

You can use Java 8's streams to solve your problem. Something like this should work:

//untested
Map<Path, List<Path>> dirToFileMap = files.stream()
            .map(f -> Paths.get(f.getAbsolutePath()))
            .collect(Collectors.groupingBy(Path::getParent));

With that map you can achieve what you need. Iterate over keySet first, for example.

Just a matter of typing; below I do not take canonical paths (Windows is case-insensitive), but the gist is clear.

So a Comparator for sorting:

public class FileComparator extends Comparator<File> {

    @Override
    public int compareTo(File lhs, File rhs) {
        if (lhs == null && rhs == null) {
            return 0;
        } else if (lhs == null || rhs == null) {
            return lhs == null ? -1 : 1;
        }
        int cmp = compareTo(lhs.getParentFile(), rhs.getParentFile());
        if (cmp == 0) {
            if (lhs.isDirectory() != rhs.isDirectory()) {
                return lhs.isDirectory() ? -1 : 1;
            }
            cmp = lhs.getName().compareTo(rhs.getName());
        }
        return cmp;
    }

    @Override
    public boolean equals(Object comparator) {
        return comparator != null && comparator.getClass().equals(getClass());
    }
}

As always the equals just compares comparators, not Files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!