java 方法 参数 引用,Java 8中方法引用的外部参数

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:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值