External argument to method reference in Java 8

前端 未结 1 1007
遥遥无期
遥遥无期 2021-01-13 14:05

I am looking to pass an external parameter to a method reference:

String prefix = \"The number is :\";
numbers.forEach(Main::printWithPrefix);

private stat         


        
1条回答
  •  广开言路
    2021-01-13 14:39

    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 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 printWithPrefix(String prefix,
                                                     Consumer 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));
    

    0 讨论(0)
提交回复
热议问题