Java8整理

1.Lambda表達式:簡潔地表示可傳遞的匿名函數的一種方式。沒有名稱,但是有參數列表,函數主體,返回類型,可能還有一個可以拋出的異常列表。

基礎語法

()->

()->{***;}

例子:

()->{}

()->"abc"

()->{return "MMM";}

(String s)->s.length()

(Apple a)->a.getWeight() >100

(int x,int y)->{System.out.println(inventory);}

()->44

方法的引用::

(Apple a1,Apple a2)->a1.getWeight(),compareTo(a2.getWeight())

(Apple a)->a.getWeight() 等效於 Apple::getWeight

(str,i)->str.substring(i) 等效於String::substring

(String s)->System.out.println(s)  等效於System.out::println


1.1 List中sort,重寫Comparator排序

List<Apple> inventory =
        Arrays.asList(new Apple(80, "green"), new Apple(155, "green"), new Apple(120, "red"));
inventory.sort((Apple a, Apple b) -> b.getWeight().compareTo(a.getWeight()));
inventory.sort(Comparator.comparing((Apple a) -> a.getWeight()));//按照重量升序 方法的引用inventory.sort(Comparator.comparing((Apple a) -> a.getWeight()).reversed());//降序
System.out.println(inventory);

可以在函數式接口上使用Lambda表達式

函數式接口就是隻定義一個抽象方法的接口

java8中提供很多函數式接口,可以直接使用

Predicate<T> 接口定義了一個test的抽象方法,接受泛型T返回Boolean

Consumer 定義了一個accept抽象方法,接受泛型T 無返回

Function<T,R> 定義了一個apply接口 接受泛型T對象  返回R對象

Supplier<T>   ()->T 傳入一個泛型T的,get方法,返回一個泛型T 類似於工廠創建對象

針對專門的輸入參數類型的函數式接口的名稱都要加上對應的原始類型前綴。(好像隱式轉換)

DoublePredicate,IntConsumer

(List<String> list)->list.isEmpty()   利用了Predicate<List<String>>

()->new Apple(10) 利用了Supplier<Apple>

(Apple a) -> System.out.println(a.getWeight()) 利用了Consumer(Apple)

(String s)-> s.length() 利用了 Function(String,Integer)或ToIntFunction<String>


任何函數式接口都不允許拋出受檢查異常(checked exception)。如果需要Lambda表達式來拋異常,有兩種辦法

定義一個自己的函數式接口,並聲明受檢異常,或者把Lambda包在一個try/catch 塊中


Stream:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章