如何将Map <path,list <path =“” >>流到包含绝对路径为String的List <string>?

时间:2019-03-26 14:54:51

标签: java java-8 java-stream tostring

我当前的项目需要一种将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>的结果?

1 个答案:

答案 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());