【问题标题】:How to stream a Map<Path, List<Path>> to a List<String> containing the absolute path as String?如何将 Map<Path, List<Path>> 流式传输到包含绝对路径为 String 的 List<String>?
【发布时间】:2019-08-17 00:19:18
【问题描述】:

我当前的项目需要一种将Map&lt;Path, List&lt;Path&gt;&gt; 转换为包含绝对路径的List&lt;String&gt; 的方法。 Map 包含 Paths 的文件,这些文件按包含它们的目录分组。
但是,我必须将找到的文件的所有绝对路径写入转储文件,这就是为什么我需要 Strings 而不是 Paths。
目前,我使用以下方法执行此操作,该方法使用嵌套的 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 或values 的Map 的一种(甚至更多)现代方式。
我遇到的问题是我只是不知道如何在流中应用file.toAbsolutePath().toString()。我只能将所有Paths 收集为List&lt;Path&gt;:

List<Path> filePaths = sqlFilesInDirectories.values().stream()
                            .flatMap(List::stream)
                            .map(Path::toAbsolutePath)
                            .collect(Collectors.toList());

我怎样才能改变这个语句(或写一个完全不同的语句),它给我想要的List&lt;String&gt;,结果为Path.toAbsolutePath().toString()?

【问题讨论】:

  • 只需添加第二个地图调用.map(Path::toAbsolutePath).map(Object::toString)
  • @Michael 哦,我没想过为此使用Object.toString()!感谢您指出这一点。

标签: java string dictionary java-8 java-stream


【解决方案1】:

您几乎完成了,您只需在生成的路径列表上调用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());

【讨论】:

  • 谢谢,第二个代码正是我需要的。第一个也很酷,但它意味着第二个陈述,我试图避免。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2020-04-01
  • 1970-01-01
  • 2018-09-22
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多