External parameters referenced by methods in Java 8
•
Java
I want to pass external parameters to method references:
String prefix = "The number is :"; numbers.forEach(Main::printWithPrefix); private static void printWithPrefix(Integer number) { System.out.println(number); }
I don't know what to do I can do this with lambda:
String prefix = "The number is :"; numbers.forEach(number -> { System.out.println(prefix + number); });
Can external parameters be passed to method references?
Solution
No, you cannot pass parameters to a method reference What you can do is create a method to return to the consumer:
private static Consumer<Integer> printWithPrefix(String prefix) { return number -> System.out.println(prefix + number); }
This can then be used as a factory for creating consumers, which you can pass to numbers forEach:
String prefix = "The number is :"; numbers.forEach(printWithPrefix(prefix));
You can even make it more generic by creating a printwithprefix method with consumer as a parameter so that you can pass in another one. If you want to:
private static Consumer<Integer> printWithPrefix(String prefix,Consumer<Integer> printer) { return number -> { System.out.print(prefix); printer.accept(number); }; }
For example, you can use the printnumber method:
private static void printNumber(Integer number) { System.out.println(number); } String prefix = "The number is :"; numbers.forEach(printWithPrefix(prefix,Main::printNumber));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码