【问题标题】:Java 8 Streams. Pass Two arguments to a method called in forEachJava 8 流。将两个参数传递给在 forEach 中调用的方法
【发布时间】:2018-12-16 17:47:11
【问题描述】:

使用 Java 8 流 API,我想要一种调用接受两个参数的引用方法的方法。 splitFileByMaxRows 是引用方法,应该将 Stringint 作为其参数。有什么方法可以实现吗?

private void breakLargeFileIntoChunks(final File setlFile, int parentFileId) {
    LOG.info(LOG.isInfoEnabled() ? "*** Breaking Large File Into Chunks ***" : null);

    try (Chunker chunker = new Chunker(); 
         Stream<String> lines = Files.lines(Paths.get(setlFile.getAbsolutePath()))) {
        lines.forEach(chunker::splitFileByMaxRows);
    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    MethodReference 只能在允许 Consumer 的地方使用。如果您还记得,消费者只接受一个输入参数。因此,在您的情况下,您有两个参数,这不可能作为方法引用传递给消费者。因此,您必须使用可以根据需要接受参数的 lambda。

    【讨论】:

      【解决方案2】:

      您不能使用方法引用,因为您无法将 int 参数传递给它。

      因此,请改用 lambda 表达式:

      lines.forEach(s -> chunker.splitFileByMaxRows(s,someInt));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        相关资源
        最近更新 更多