java lambda 表达式中的双冒号的用法说明 ::

2022-07-29,,,,

冒号运算就是java中的[方法引用],[方法引用]的格式是

类名::方法名

注意是方法名哦,后面没有括号“()”哒。为啥不要括号,因为这样的是式子并不代表一定会调用这个方法。这种式子一般是用作lambda表达式,lambda有所谓懒加载嘛,不要括号就是说,看情况调用方法。

例如

表达式:

person -> person.getage();

可以替换成

person::getage

表达式

() -> new hashmap<>();

可以替换成

hashmap::new

这种[方法引用]或者说[双冒号运算]对应的参数类型是function<t,r> t表示传入类型,r表示返回类型。比如表达式person -> person.getage(); 传入参数是person,返回值是person.getage(),那么方法引用person::getage就对应着function<person,integer>类型。

下面这段代码,进行的操作是,把list<string>里面的string全部大写并返还新的arraylist<string>,在前面的例子中我们是这么写的:

@test
public void converttest() {
  list<string> collected = new arraylist<>();
  collected.add("alpha");
  collected.add("beta");
  collected = collected.stream().map(string -> string.touppercase()).collect(collectors.tolist());
  system.out.println(collected);
}

现在也可以被替换成下面的写法:

@test
public void converttest() {
  list<string> collected = new arraylist<>();
  collected.add("alpha");
  collected.add("beta");
  collected = collected.stream().map(string::touppercase).collect(collectors.tocollection(arraylist::new));//注意发生的变化
  system.out.println(collected);
}

补充知识:java解析属性配置文件并给占位符传参

我就废话不多说了,大家还是直接看代码吧~

//注册功能
public void register(user user){
//补齐数据
user.setuid(commonutils.uuid());
user.setstatus(false);
user.setactivationcode(commonutils.uuid() + commonutils.uuid());
try {
userdao.save(user);
} catch (exception e) {
throw new runtimeexception();
}
//发送邮件
//加载配置文件
properties properties = new properties();
try {
properties.load(this.getclass().getclassloader().getresourceasstream("email_template.properties"));
} catch (ioexception e1) {
throw new runtimeexception();
}
string host = properties.getproperty("host");
string username = properties.getproperty("username");
string password = properties.getproperty("password");

string from = properties.getproperty("from");
string to = user.getemail();
string subject = properties.getproperty("subject");
//把占位符用后面的参数替换,后面参数可变
string content = messageformat.format(properties.getproperty("content"), user.getactivationcode());

//发送邮件3步曲
session session = mailutils.createsession(host, username, password);
mail mail = new mail(from, to, subject, content);
try {
mailutils.send(session, mail);
} catch (exception e) {
throw new runtimeexception();
}
}

以上这篇java lambda 表达式中的双冒号的用法说明 ::就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《java lambda 表达式中的双冒号的用法说明 ::.doc》

下载本文的Word格式文档,以方便收藏与打印。