【问题标题】:Add images from folder to arraylist using stream使用流将图像从文件夹添加到数组列表
【发布时间】:2018-10-17 18:40:35
【问题描述】:

我正在尝试从文件夹路径作为参数传入的文件夹中读取图像,我正在尝试使用流 API 将它们添加到数组列表中,但我不知道我应该使用什么变量在 forEach() 中添加到我的数组列表中

    public void downsampling(String inputPath, String outputPath) {
    ArrayList<BufferedImage> inputSequence = new ArrayList<BufferedImage>();

    try (Stream<Path> paths = Files.walk(Paths.get(inputPath))) {
        paths
                .forEach(inputSequence.add(XXX));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

XXX 应该换成什么?非常感谢

【问题讨论】:

  • .forEach(x -&gt; inputSequence.add(x));
  • 工作得很好,谢谢!
  • 最好使用inputSequence = paths.map(…).collect(Collectors.toList()); 但是为什么要将这些图像收集到List 中呢?看来,您的方法应该处理它们,而不是返回它们,所以只需一个一个处理它们,而不将它们添加到List
  • 嗯,是的,我确实可以在不将它们添加到列表的情况下处理它们,但这是当时想到的,但它仍然有效,谢谢你接下来我会尝试使用你的建议时间。

标签: java arrays arraylist stream java-stream


【解决方案1】:

代码不完整,因为我还应该进行下采样,而且我刚刚完成输入,当我评论“工作”时,我的意思是 @Eran 的评论帮助我正确引用了即时流式传输的文件的变量引用,这里是到目前为止有效的输入代码,无需对我投反对票......

    public void downsampling(String inputPath, String outputPath) {
    ArrayList<BufferedImage> inputSequence = new ArrayList<BufferedImage>();

    try (Stream<Path> paths = Files.walk(Paths.get(inputPath))) {
        paths
                .forEach(x -> {
                    try {
                        inputSequence.add(ImageIO.read((InputStream) x));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多