I am looking to pass an external parameter to a method reference:
String prefix = "The number is :";
numbers.forEach(Main::printWithPrefix);
private static void printWithPrefix(Integer number) {
System.out.println(number);
}
I am no idea on how to do it. I am able to do it with a lambda:
String prefix = "The number is :";
numbers.forEach(number -> {
System.out.println(prefix + number);
});
Is it possible to pass an external parameter to a method reference?
No, you cannot pass a parameter to a method reference. What you can do is create a method which returns a
Consumer
:This then works as a factory for creating a
Consumer
that you can pass tonumbers.forEach
:You can even make it a bit more general, creating a
printWithPrefix
method that takes aConsumer
as an argument so that you could pass in a different one if you'd want to:You could use it, for example, with a
printNumber
method: