java lambda表示式用法總結
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了java lamda表示式用法總結,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
1、什麼是函數語言程式設計(百度百科上的解釋)
2、為什麼要使用函數語言程式設計(有什麼好處)
1、程式碼簡潔,減少程式碼量
2、接近自然語言,容易理解
傳統實現分組
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表示式
Map<String,List<Student>> maps = student.stream.collect(Collerctor.groupBy(Student :: getSex));
3、很好實現併發處理
3、什麼是lambda表示式
1、方法體為表示式,使用return將表達結果返回回去
(paramates)-> expression
(a,b) -> return a + b
2、方法體為程式碼塊,必須用{}包含起來,且需要使用return返回值,但是如果程式碼塊返回的是void,那麼不需要返回值
(parameter) -> {statements;}
(int a) -> (System.out.println(a))
(int a) -> (return a*a);
4、lambda的底層實現
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其實是繼承BinaryOperator的一個匿名內部類
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。