External argument to method reference in Java 8

旧时模样 提交于 2019-12-04 01:40:35

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/38697939/external-argument-to-method-reference-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!