简体   繁体   English

Java 8 流。 将两个参数传递给在 forEach 中调用的方法

[英]Java 8 Streams. Pass Two arguments to a method called in forEach

Using Java 8 streams API, I want a way to call a reference method which accepts two arguments.使用 Java 8 流 API,我想要一种方法来调用接受两个参数的引用方法。 splitFileByMaxRows is the reference method that should take a String and an int as its arguments. splitFileByMaxRows是应该将Stringint作为其参数的引用方法。 Is there any way to achieve it?有什么方法可以实现吗?

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();
    }

}

You can't use a method reference, since you have no way of passing the int argument to it. 您无法使用方法引用,因为您无法将int参数传递给它。

Therefore, use a lambda expression instead: 因此,请改用lambda表达式:

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

A MethodReference can be used only in the place where a Consumer is allowed. MethodReference 只能在允许使用 Consumer 的地方使用。 If you recollect a Consumer takes in only one input parameter.如果你记得一个消费者只接受一个输入参数。 So in your case you have two arguments, this is not possible to be passed in as Method reference to a consumer.因此,在您的情况下,您有两个参数,这是不可能作为方法引用传递给消费者的。 So you have to use a lambda that can take arguments as necesssary.因此,您必须使用可以根据需要接受参数的 lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在forEach中执行操作并将其传递给groupingBy在Java流中 - How to perform operations in forEach and pass it to groupingBy in Java streams 每个Java 8流 - Java 8 streams forEach Java 8 个流。 如何将每个枚举类型的 BigDecimal 总计聚合到自定义 bean - Java 8 streams. How to aggregate BigDecimal totals per enumerated type into a custom bean Java-forEach的基本流用法 - Java - Basic streams usage of forEach 在Java中将许多参数传递给方法的最佳方法 - best way to pass many arguments to a method in Java 如何将新数组作为参数传递给Java中的方法? - How to pass a new array as arguments to a method in Java? Java:如何将动态数量的参数传递给方法 - Java: How to pass a dynamic amount of arguments to a method 转换 Map <string,list<person> &gt; 至 Map <string,list<employee> &gt;,使用 Java 8 个流。 我这样做了,但是没有 for 循环怎么做</string,list<employee></string,list<person> - Convert Map<String,List<Person>> to Map<String,List<Employee>>, using Java 8 streams. I did this but how do this without for loop "我可以将数组作为参数传递给 Java 中具有可变参数的方法吗?" - Can I pass an array as arguments to a method with variable arguments in Java? 如果将从外壳程序调用Java程序,哪种方法传递参数更好? - If a java program will be called from shell, which way is better to pass the arguments?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM