【问题标题】:Getting child elements from list of String paths从字符串路径列表中获取子元素
【发布时间】:2021-01-29 02:42:27
【问题描述】:

如果我有一个字符串路径列表

Mammal/

Mammal/Pet/

Mammal/Pet/Dog/

Mammal/Pet/Cat/

Bird/

Bird/Blah/

Bird/Blah/Parrot/

Bird/Blah/Parrot/Feather/

我只想要孩子最多的元素

Mammal/Pet/Dog/

Mammal/Pet/Cat/

Bird/Blah/Parrot/Feather/

我怎样才能比现在做得更好?

我当前的代码写得不是很好,但它确实有效

List<String> paths = ...;
List<String> children = new ArrayList<String>();
if(paths.size()==1){children.add(paths.get(0));}
for(int i=1; i < paths.size(); i++){
    //Found a local maximum in number of "/"'s
    if(paths.get(i).split("/").length <= paths.get(i-1).split("/").length){
        children.add(paths.get(i-1));
    }
    else if(i==paths.size()-1){
        children.add(paths.get(i));
    }
}

【问题讨论】:

  • 你写的字符串随机出现会怎样?

标签: java string algorithm


【解决方案1】:

您可以使用 Files.walkFileTree(),在进行过程中添加“叶子”目录。参数是起始路径和 SimpleFileVisitor 实现。访问者只需检查当前目录中的文件,如果这些文件本身都不是目录,则将该目录添加到路径集中。

Path start = Paths.get(...); // e.g. directory.getCanonicalPath()
Set<Path> leafDirectories = new HashSet<>();
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        File[] subdirectories = dir.toFile().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        });
    
        if (subdirectories.length == 0)
            leafDirectories.add(dir);
    
        return FileVisitResult.CONTINUE;
    }
});
// print leaf directories
leafDirectories.stream().forEach(dir -> System.out.println(dir));

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2018-12-31
    • 2019-01-28
    • 1970-01-01
    • 2019-05-25
    • 2021-12-07
    相关资源
    最近更新 更多