溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java lambda表達(dá)式用法總結(jié)

發(fā)布時(shí)間:2020-10-14 13:59:22 來源:腳本之家 閱讀:154 作者:張小澤的小號(hào) 欄目:編程語言

這篇文章主要介紹了java lamda表達(dá)式用法總結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1、什么是函數(shù)式編程(百度百科上的解釋)

java lambda表達(dá)式用法總結(jié)

2、為什么要使用函數(shù)式編程(有什么好處)

1、代碼簡潔,減少代碼量

2、接近自然語言,容易理解

傳統(tǒng)實(shí)現(xiàn)分組

List<Student> students;
Map<String,List<Student>> maps = Maps.newHashMap();
for(Student student : students){
  List<Student> studentList =  students.getOrDefault(student.getSex(), Lists.newArrayList());
  studentList.add(student);
  maps.put(student.getSex(), studentList);
}

使用lambda表達(dá)式

Map<String, List<Student>> maps = student.stream.collect(Collerctor.groupBy(Student :: getSex));

3、很好實(shí)現(xiàn)并發(fā)處理

3、什么是lambda表達(dá)式

1、方法體為表達(dá)式,使用return將表達(dá)結(jié)果返回回去

 ?。╬aramates)-> expression

   (a, b) -> return a + b

2、方法體為代碼塊,必須用{}包含起來,且需要使用return返回值,但是如果代碼塊返回的是void,那么不需要返回值

  (parameter) -> {statements;}   

  (int a) -> (System.out.println(a))

  (int a) -> (return a*a);

4、lambda的底層實(shí)現(xiàn)

BinaryOperator binaryOperator = (int a, int b) -> {return a + b;};
if(binaryOperator instanceof BinaryOperator){System.out.println(binaryOperator.getClass());}
int sum = binaryOperator.applyAsInt(2,3);
System.out.println(sum);

可以看出來binaryOperator其實(shí)是繼承BinaryOperator的一個(gè)匿名內(nèi)部類

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI