看如下一行代碼
public class Car { public static Car create(Supplier<Car> supplier){ return supplier.get(); } public static void main(String[] args) { Car car = Car.create(Car::new); List<Integer> integers = new ArrayList<>(); integers.stream().mapToInt(Integer::intValue).sum(); integers.stream().mapToLong(Long::valueOf).sum(); }}
生成Car對象用Car::new
獲取Integer的int值採用Integer::intValue
將Integer轉化成Long採用Long::valueOf即可。
你是否會疑惑這個神奇的&34;是什麼?
這就是我們Java8中的新特性方法引用。
我們可以用一對冒號&34;,通過方法的名字來指向一個方法,可以使語言的構造更緊湊簡潔,減少冗餘代碼。
疑惑,那Car::new返回的是什麼呢?是Car對象嗎?
Car car = Car::new; 報錯Supplier<Car> carSupplier = Car::new; 正確
Car::new 返回的是 Supplier<Car> 對象,生成Car 是carSupplier.get時候初始化。
那Integer::intValue呢?
這裡是調用了Integer的iniValue方法。為什麼可以這樣使用呢?
//錯誤示例int result = Integer::intValue; //正確ToIntFunction<Integer> intFunction = Integer::intValue;
再來看一個例子
ToIntFunction<Integer> intFunction = Integer::valueOf;ToIntFunction<Integer> intFunction2 = Integer::intValue;這兩個都是返回的都是ToIntFunction<Integer>
JAVA8中&34;把函數變成了參數,傳遞到函數裡面
但是&34;為什麼把Car::new轉化成了Supplier<Car>,Integer::valueOf轉化成了ToIntFunction<Integer>呢?
來看Supplier
@FunctionalInterfacepublic interface Supplier<T> { /** * Gets a result. * * @return a result */ T get();}
Supplier有一個get()方法,不需要傳入參數返回T對象。
Car的new方法,默認構造方法,不需要傳入參數,返回Car對象。
說到這裡還不明白的話,看下面這個例子。
public class Car { public static Car generate(){ return new Car(); } public static void main(String[] args) { Supplier<Car> car= Car::generate; }}
Car::generate同樣是返回的是Supplier<Car>,generate沒有參數,返回的是Car對象,剛好跟Supplier符合。
說到這裡相信大概大家明白了,&34;將我們的方法轉化成了對應的函數式接口
舉個例子
ToIntFunction類
@FunctionalInterfacepublic interface ToIntFunction<T> { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result */ int applyAsInt(T value);}
參數是T,返回int對象。如果我們要使用&34;該如何做呢?
public class Car { public static int test(int tst){ return 1; } public static void main(String[] args) { ToIntFunction<Integer> integerToIntFunction = Car::test; }}
我們只要定義一個方法,有一個輸入參數,返回參數是int即可。
講到這裡,我們用Java8將List<Integer>轉化成List<Long>怎麼處理呢?
我們看到stream裡面有一個方法
/** * Returns a stream consisting of the results of applying the given * function to the elements of this stream. * * <p>This is an <a href=&StreamOps&34;package-summary.html34;>non-interfering</a>, * <a href=&Statelessness&34;::&34;::"的地方,我們先觀察函數參數是什麼,需要什麼參數,返回什麼對象。然後找對應的處理的方法即可。
當然,Java 8 函數式接口遠不止這些。
但是用起來了,讓自己的代碼帥起來就行。