java – 在lamdas中工作的方法引用赋值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 在lamdas中工作的方法引用赋值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2243字,纯文字阅读大概需要4分钟。
内容图文
![java – 在lamdas中工作的方法引用赋值](/upload/InfoBanner/zyjiaocheng/735/41cb03f2cf15476fb1cd7597e2a4e386.jpg)
嗨问题很简单.
String :: startWith和“”:: startWith有什么区别?
解决方法:
String :: startWith将startWith()方法应用于lambda的第一个参数.
“”:: startWith将startWith()方法应用于“”文字或以更广泛的方式应用于未声明为lambda参数的变量.
更详尽的是,这两种提供方法参考的方法是不可替代的.
假设您要对public boolean startsWith(String prefix)方法使用方法引用.我在方法重载时指定它.
使用lambda参数的方法引用旨在与BiPredicate< String,String>一起使用.函数接口,而使用未在lambda参数中声明的变量的方法引用被设计为使用Predicate< String>功能界面.
>将变量作为方法引用的目标传递的方式:
字符串myVariable;
MYVARIABLE :: startWith
提供了应该应用方法引用的String.这里:myVariable.
因此,只需要在lambda中传递prefix参数.
所以Predicate< String>西装.
>使用lambda参数的第一个参数作为方法引用的目标的方法:
字符串:: startsWith
不提供应该应用方法引用的String.
因此,应该在其上调用方法的String和前缀参数都需要在lambda中传递.
所以BiPredicate< String,String>西装.
这是一个示例代码来说明:
public static void main(String[] args) {
// using method reference with lambda parameter
myMethodWithBiPredicate((s, prefix) -> s.startsWith(prefix), "mystring", "my");
myMethodWithBiPredicate(String::startsWith, "mystring", "my");
// using method reference with variable not in lambda parameter
String stringNotInLambdaParams = "stringNotInParam";
Predicate<String> functionPredicate = stringNotInLambdaParams::startsWith;
System.out.print("myMethodWithBiPredicate with string "
+ "(included in the method reference)="
+ stringNotInLambdaParams
+ " and prefix= string | Result = ");
myMethodWithPredicate(functionPredicate, "string");
}
public static void myMethodWithBiPredicate(BiPredicate<String, String> function,
String string,
String prefix) {
System.out.println("myMethodWithBiPredicate with string="
+ string + " and prefix= " + prefix
+ " | Result = " + function.test(string, prefix));
}
public static void myMethodWithPredicate(Predicate<String> function, String prefix) {
System.out.println(function.test(prefix));
}
产生这个输出:
myMethodWithBiPredicate with string=mystring and prefix= my | Result
= truemyMethodWithBiPredicate with string=mystring and prefix= my | Result
= truemyMethodWithPredicate with string (included in the method
reference)=stringNotInParam and prefix= string | Result = true
内容总结
以上是互联网集市为您收集整理的java – 在lamdas中工作的方法引用赋值全部内容,希望文章能够帮你解决java – 在lamdas中工作的方法引用赋值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。