[英]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
是应该将String
和int
作为其参数的引用方法。 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.