java lambda 表达式中的双冒号的用法说明 ::
双冒号运算就是Java中的[方法引用],[方法引用]的格式是
类名::方法名
注意是方法名哦,后面没有括号“()”哒。为啥不要括号,因为这样的是式子并不代表一定会调用这个方法。这种式子一般是用作Lambda表达式,Lambda有所谓懒加载嘛,不要括号就是说,看情况调用方法。
例如
表达式:
person->person.getAge();
可以替换成
Person::getAge
表达式
()->newHashMap<>();
可以替换成
HashMap::new
这种[方法引用]或者说[双冒号运算]对应的参数类型是Function
下面这段代码,进行的操作是,把List
@Test
publicvoidconvertTest(){
Listcollected=newArrayList<>();
collected.add("alpha");
collected.add("beta");
collected=collected.stream().map(string->string.toUpperCase()).collect(Collectors.toList());
System.out.println(collected);
}
现在也可以被替换成下面的写法:
@Test
publicvoidconvertTest(){
Listcollected=newArrayList<>();
collected.add("alpha");
collected.add("beta");
collected=collected.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));//注意发生的变化
System.out.println(collected);
}
补充知识:Java解析属性配置文件并给占位符传参
我就废话不多说了,大家还是直接看代码吧~
//注册功能
publicvoidregister(Useruser){
//补齐数据
user.setUid(CommonUtils.uuid());
user.setStatus(false);
user.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());
try{
userDao.save(user);
}catch(Exceptione){
thrownewRuntimeException();
}
//发送邮件
//加载配置文件
Propertiesproperties=newProperties();
try{
properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
}catch(IOExceptione1){
thrownewRuntimeException();
}
Stringhost=properties.getProperty("host");
Stringusername=properties.getProperty("username");
Stringpassword=properties.getProperty("password");
Stringfrom=properties.getProperty("from");
Stringto=user.getEmail();
Stringsubject=properties.getProperty("subject");
//把占位符用后面的参数替换,后面参数可变
Stringcontent=MessageFormat.format(properties.getProperty("content"),user.getActivationCode());
//发送邮件3步曲
Sessionsession=MailUtils.createSession(host,username,password);
Mailmail=newMail(from,to,subject,content);
try{
MailUtils.send(session,mail);
}catch(Exceptione){
thrownewRuntimeException();
}
}
以上这篇javalambda表达式中的双冒号的用法说明::就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。