我当前的项目需要一种将Map<Path, List<Path>>
转换为包含绝对路径的List<String>
的方法。 Map
包含Path
个文件,这些文件由包含它们的目录分组。
但是,我必须将找到的文件的所有绝对路径写入转储文件,这就是为什么我需要String
而不是Path
的原因。
目前,我使用以下方法来实现此目的,该方法在forEach
及其值上使用嵌套的Map
调用:
public List<String> getAllAbsolutePaths(Map<Path, List<Path>> filesInPath) {
List<String> absolutePaths = new ArrayList<String>();
filesInPath.forEach((directory, files) -> {
files.forEach(file -> absolutePaths.add(file.toAbsolutePath().toString()));
});
return absolutePaths;
}
这是可行的,但是我只是想知道一种流式传输keySet
的{{1}}或values
的现代方法。
我的问题是我只是不知道如何在流中应用Map
。我可以将所有file.toAbsolutePath().toString()
收集为Path
:
List<Path>
我该如何更改此语句(或写一个完全不同的语句),使我得到所需的List<Path> filePaths = sqlFilesInDirectories.values().stream()
.flatMap(List::stream)
.map(Path::toAbsolutePath)
.collect(Collectors.toList());
并得到List<String>
的结果?
答案 0 :(得分:3)
您快完成了,只需要在生成的路径列表上调用toString
:
List<String> strings = filePaths.stream()
.map(Object::toString)
.collect(Collectors.toList());
或直接在您的信息流中
List<String> filePaths = sqlFilesInDirectories.values().stream()
.flatMap(List::stream)
.map(Path::toAbsolutePath)
.map(Object::toString)
.collect(Collectors.toList());