Java8如何获取指定根路径下一级子目录与其下一级子目录列表的Map映射
实现方案
你不需要用递归,直接用Files.walk设置遍历深度为2即可覆盖你需要的所有目录层级:深度0是输入的根目录,深度1是作为Map key的一级子目录,深度2是作为value元素的二级子目录。
Java 9+ 版本实现
可以直接使用Collectors.filtering完成过滤收集:
public Map<String, List<String>> getSubDirMapping(String rootDir) throws IOException { Path rootPath = Paths.get(rootDir); try (Stream<Path> stream = Files.walk(rootPath, 2)) { return stream .filter(Files::isDirectory) // 排除根目录本身 .filter(path -> !path.equals(rootPath)) .collect(Collectors.groupingBy( // 提取分组的key:即一级子目录名称 path -> path.getParent().equals(rootPath) ? path.getFileName().toString() : path.getParent().getFileName().toString(), // 收集对应一级目录下的二级子目录名称 Collectors.mapping( path -> path.getParent().equals(rootPath) ? null : path.getFileName().toString(), Collectors.filtering(Objects::nonNull, Collectors.toList()) ) )); } }
Java 8 兼容版本实现
Java8没有内置Collectors.filtering,可以拆分两步实现,同时也能保证没有二级子目录的一级目录也会出现在结果中,对应value为空列表:
public Map<String, List<String>> getSubDirMappingJava8(String rootDir) throws IOException { Path rootPath = Paths.get(rootDir); // 第一步:先获取所有一级子目录,初始化结果Map Set<String> firstLevelDirs = Files.list(rootPath) .filter(Files::isDirectory) .map(p -> p.getFileName().toString()) .collect(Collectors.toSet()); Map<String, List<String>> result = new HashMap<>(); firstLevelDirs.forEach(dir -> result.put(dir, new ArrayList<>())); // 第二步:遍历二级子目录,填充结果 try (Stream<Path> stream = Files.walk(rootPath, 2)) { stream.filter(Files::isDirectory) // 只保留二级子目录(父目录的父目录是根目录) .filter(path -> { Path parent = path.getParent(); return parent != null && parent.getParent() != null && parent.getParent().equals(rootPath); }) .forEach(path -> { String parentDirName = path.getParent().getFileName().toString(); result.get(parentDirName).add(path.getFileName().toString()); }); } return result; }
内容的提问来源于stack exchange,提问作者curious_brain
相关产品推荐
相关产品推荐

