java lambda 表達(dá)式中的雙冒號(hào)的用法說明 ::
雙冒號(hào)運(yùn)算就是Java中的[方法引用],[方法引用]的格式是
類名::方法名
注意是方法名哦,后面沒有括號(hào)“()”噠。為啥不要括號(hào),因?yàn)檫@樣的是式子并不代表一定會(huì)調(diào)用這個(gè)方法。這種式子一般是用作Lambda表達(dá)式,Lambda有所謂懶加載嘛,不要括號(hào)就是說,看情況調(diào)用方法。
例如
表達(dá)式:
person -> person.getAge();
可以替換成
Person::getAge
表達(dá)式
() -> new HashMap<>();
可以替換成
HashMap::new
這種[方法引用]或者說[雙冒號(hào)運(yùn)算]對(duì)應(yīng)的參數(shù)類型是Function<T,R> T表示傳入類型,R表示返回類型。比如表達(dá)式person -> person.getAge(); 傳入?yún)?shù)是person,返回值是person.getAge(),那么方法引用Person::getAge就對(duì)應(yīng)著Function<Person,Integer>類型。
下面這段代碼,進(jìn)行的操作是,把List<String>里面的String全部大寫并返還新的ArrayList<String>,在前面的例子中我們是這么寫的:
@Testpublic 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);}
現(xiàn)在也可以被替換成下面的寫法:
@Testpublic void convertTest() { List<String> collected = new ArrayList<>(); collected.add('alpha'); collected.add('beta'); collected = collected.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));//注意發(fā)生的變化 System.out.println(collected);}
補(bǔ)充知識(shí):Java解析屬性配置文件并給占位符傳參
我就廢話不多說了,大家還是直接看代碼吧~
//注冊(cè)功能public void register(User user){//補(bǔ)齊數(shù)據(jù)user.setUid(CommonUtils.uuid());user.setStatus(false);user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid());try {userDao.save(user);} catch (Exception e) {throw new RuntimeException();}//發(fā)送郵件//加載配置文件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');//把占位符用后面的參數(shù)替換,后面參數(shù)可變String content = MessageFormat.format(properties.getProperty('content'), user.getActivationCode());//發(fā)送郵件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 表達(dá)式中的雙冒號(hào)的用法說明 ::就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP編碼必備的8條原則2. 使用css實(shí)現(xiàn)全兼容tooltip提示框3. 一文帶你搞懂JavaScript中的進(jìn)制與進(jìn)制轉(zhuǎn)換4. 匹配模式 - XSL教程 - 45. 詳解JS前端使用迭代器和生成器原理及示例6. 得到XML文檔大小的方法7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. ASP基礎(chǔ)知識(shí)Command對(duì)象講解9. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)10. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
