国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

java lambda 表達(dá)式中的雙冒號的用法說明 ::

瀏覽:94日期:2022-08-25 08:04:17

雙冒號運(yùn)算就是Java中的[方法引用],[方法引用]的格式是

類名::方法名

注意是方法名哦,后面沒有括號“()”噠。為啥不要括號,因?yàn)檫@樣的是式子并不代表一定會調(diào)用這個方法。這種式子一般是用作Lambda表達(dá)式,Lambda有所謂懶加載嘛,不要括號就是說,看情況調(diào)用方法。

例如

表達(dá)式:

person -> person.getAge();

可以替換成

Person::getAge

表達(dá)式

() -> new HashMap<>();

可以替換成

HashMap::new

這種[方法引用]或者說[雙冒號運(yùn)算]對應(yīng)的參數(shù)類型是Function<T,R> T表示傳入類型,R表示返回類型。比如表達(dá)式person -> person.getAge(); 傳入?yún)?shù)是person,返回值是person.getAge(),那么方法引用Person::getAge就對應(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ǔ)充知識:Java解析屬性配置文件并給占位符傳參

我就廢話不多說了,大家還是直接看代碼吧~

//注冊功能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á)式中的雙冒號的用法說明 ::就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 丹江口市| 五家渠市| 正安县| 郧西县| 高要市| 鄄城县| 保亭| 十堰市| 高台县| 聂拉木县| 通化市| 南川市| 县级市| 子洲县| 丘北县| 通许县| 启东市| 巫溪县| 华安县| 屯门区| 许昌市| 法库县| 明星| 揭东县| 辽宁省| 台湾省| 五家渠市| 宝鸡市| 永胜县| 紫云| 通辽市| 望江县| 济宁市| 海安县| 北京市| 华容县| 临泽县| 商都县| 四平市| 韶关市| 静乐县|