雙冒號運算就是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>,在前面的例子中我們是這么寫的:
1
2
3
4
5
6
7
8
|
@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); } |
現在也可以被替換成下面的寫法:
1
2
3
4
5
6
7
8
|
@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解析屬性配置文件并給占位符傳參
我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//注冊功能 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 表達式中的雙冒號的用法說明 ::就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_37770552/article/details/77905826