【问题标题】:Is there a way to convert the results of Stream into Array and iterate through Array elements?有没有办法将 Stream 的结果转换为 Array 并遍历 Array 元素?
【发布时间】:2019-04-07 02:11:33
【问题描述】:

我创建了一个Stream 以递归方式运行多个文件和文件夹。我需要将Stream 的结果转换为Array 并遍历Array 的结果。

以下代码有问题:

try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
        List<String> collect = stream
            .stream().map(x->x.getName())
            .filter(s -> s.toString().endsWith(".txt"))
            .sorted()
            .collect(Collectors.toList())
            .toArray();

        collect.forEach(System.out::println);
    }

    String[] listfiles = new String[stream.length];
    for (int i = 0; i < stream.length; i++) {
       listfiles[i] = stream[].getName();
    }

【问题讨论】:

  • 什么问题?编译错误?运行时错误?它运行但“不起作用”?
  • 我遇到的问题如下:The method stream() is undefined for the type Stream&lt;Path&gt;stream cannot be resolved to a variable
  • 删除.stream() 调用。

标签: java arrays stream java-stream


【解决方案1】:

您发布的代码存在一些问题。

  1. 您拨打stream.stream()
    • Stream 类没有stream() 方法。因为它已经是一个流,所以拥有这样的方法是没有意义的。
  2. 您拨打x.getName()
    • 此时,x 是一个 Path,它没有 getName() 方法。您可以使用getFileName(),它返回一个Path,或toString(),它以字符串的形式返回路径,或者将两者结合起来仅以字符串的形式获取文件名。
  3. 您将List&lt;String&gt; collect 分配给Collection.toArray() 的结果。
    • 该方法返回一个Object[]
  4. 在调用toArray() 之前使用collect(Collectors.toList())
    • Stream 类有一个 toArray() 方法,如果数组是所需的最终结果,则没有理由先收集到列表中。
  5. 您使用toArray(),它返回Object[](对于StreamCollection
  6. 您在try 块之外使用stream
    • 由于streamtry 块的本地,您不能在try 块之外使用它。您也没有理由在块外使用它,因为您只需要 String[] 结果。
  7. 您尝试执行stream[] 之类的操作。
    • Stream 不是数组,不能像数组一样访问。此外,Stream 不是容器而是管道;试图访问其中的某些元素是没有意义的。
    • 这也适用于stream.length,因为Stream 没有length 字段(同样,因为它不是数组)。

解决这些问题后,您的代码可能如下所示(基于您的代码的当前形式,因为我不确定您到底要做什么):

String[] result;
try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
    result = stream.map(Path::toString)
            .filter(s -> s.endsWith(".txt"))
            .sorted()
            .toArray(String[]::new);
}

for (int i = 0; i < result.length; i++) {
    // do something
}

您也可以考虑使用Files.find(Path,int,BiPredicate,FileVisitOption...) 和/或PathMatcher

【讨论】:

  • 我需要迭代结果并将结果添加到新数组中。我正在尝试这个但没有得到回复。 String[] listfiles = result; for (int i = 0; i &lt; result.length; i++) { listfiles[i]; System.out.println("Filename is " + listfiles[i]); }
  • "listFiles[i];" 什么都不做。如果要复制,则必须实际将元素从一个数组添加到另一个数组。例如:listFiles[i] = result[i];。阅读The Java™ Tutorials 或一些other tutorials,可能会对您有所帮助。
  • 这是最后一个问题:如何将数组从String[] 转换为File[]?还是直接从Stream获取File[]
  • 您可能可以从String 创建一个File(即使用File 的构造函数之一)。或者,如果您更改代码使其不会将Path 映射到String,您可以使用Path.toFile()
  • 我已经修改了代码,但是现在过滤器出现错误endsWithFile[] result; try (Stream&lt;Path&gt; stream = Files.walk(start, Integer.MAX_VALUE)) { result = stream.map(Path::toFile) .filter(s -&gt; s.endsWith(".ttl")) .sorted() .toArray(File[]::new); }
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2019-02-03
  • 2021-07-05
  • 2015-01-09
  • 2021-06-28
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
相关资源
最近更新 更多