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?
Static method reference operator, we use the :: operator, and that we don't pass arguments to the method reference. In general, we don't have to pass arguments to method references.
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
A method reference is similar to lambda expression used to refer a method without invoking it while constructor reference used to refer to the constructor without instantiating the named class.
No, you cannot pass a parameter to a method reference. What you can do is create a method which returns a Consumer
:
private static Consumer<Integer> printWithPrefix(String prefix) {
return number -> System.out.println(prefix + number);
}
This then works as a factory for creating a Consumer
that you can pass to numbers.forEach
:
String prefix = "The number is :";
numbers.forEach(printWithPrefix(prefix));
You can even make it a bit more general, creating a printWithPrefix
method that takes a Consumer
as an argument so that you could pass in a different one if you'd want to:
private static Consumer<Integer> printWithPrefix(String prefix,
Consumer<Integer> printer) {
return number -> {
System.out.print(prefix);
printer.accept(number);
};
}
You could use it, for example, with a printNumber
method:
private static void printNumber(Integer number) {
System.out.println(number);
}
String prefix = "The number is :";
numbers.forEach(printWithPrefix(prefix, Main::printNumber));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With