java8-Lambda表達式

u=3305436623,3058662916&fm=26&gp=0.jpg

Lambda表達式可以理解為匿名函數(shù)的一種方式:

  • 匿名 -- 說匿名,是因為它不像普通的方法那樣有一個明確的方法名稱
  • 函數(shù) -- 說它是函數(shù),是因為Lambda函數(shù)不像方法那樣屬于某一個特定的類,但是和方法一樣,Lambda有參數(shù)列表,函數(shù)主體,返回類型,還可能有拋出的異常列表
  • 傳遞 -- 可以作為參數(shù)傳遞給方法或者存儲在變量中
  • 簡潔 -- 無需向匿名類那樣寫很多的模板代碼

Lambda表達式由參數(shù)、箭頭、主體組成
匿名:

Comparator<Apple> byWeight = new Comparator<Apple>() {
 public int compare(Apple a1, Apple a2){
 return a1.getWeight().compareTo(a2.getWeight());
 }
}; 

Lambda表達式:

Comparator<Apple> byWeight =
 (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()); 

或者

Comparator<Apple> byWeight =
 (Apple a1, Apple a2) -> {
      return a1.getWeight().compareTo(a2.getWeight()); 
  }

錯誤示例

 //return 是一個控制流語句,需要使用{}
 (Apple a1, Apple a2) -> return a1.getWeight().compareTo(a2.getWeight()); 

方法引用
之前

inventory.sort((Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())); 

之后(使用方法引用和java.util.Comparator.comparing):

inventory.sort(comparing(Apple::getWeight)); 

復合Lambda表達式的用法

  • 比較器復合
    1.逆序
//按重量遞減排序
inventory.sort(comparing(Apple::getWeight).reversed());

2.比較器鏈

//thenComparing方法接受一個函數(shù)做參數(shù),如果兩個對象用第一個Comparator比較之后是一樣的,就提供第二個Cpmparator進行比較
inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry)); 
  • 謂詞復合

謂詞接口包含三個方法:negate,and,or

//產(chǎn)生現(xiàn)有Predicate對象redApple的非
Predicate<Apple> notRedApple = redApple.negate();
鏈接兩個謂詞來生成另一個Predicate對象
Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150);
鏈接Predicate的方法來構(gòu)造更復雜Predicate對象
Predicate<Apple> redAndHeavyAppleOrGreen = redApple.and(a -> a.getWeight() > 150).or(a -> "green".equals(a.getColor())); 

and 和 or方法是按照在表達式鏈中的位置,從左向右確定優(yōu)先級的,因此,a.or(b).and(c) 等價于
(a || b)&& c

  • 函數(shù)復合

Function接口提供了andThen和compose兩個默認方法,他們都會返回一個Function的一個實例

     Function<Integer, Integer> f = x -> x + 1;
     Function<Integer, Integer> g = x -> x * 2;
     Function<Integer, Integer> h = f.andThen(g);   // 等價于數(shù)學表達式 g(f(x))
     Function<Integer, Integer> m = f.compose(g);   // 等價于數(shù)學表達式 f(g(x))
     int result = h.apply(1);  //結(jié)果為4
     int result1 = m.apply(1); //結(jié)果為3
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容