Java8 Lamdba表達式

Lambda語法

定義

可以把Lambda表達式理解爲簡潔地表示可傳遞的匿名函數的一種方式:它沒有名稱,但它
有參數列表、函數主體、返回類型,可能還有一個可以拋出的異常列表。這個定義夠大的,讓我
們慢慢道來。
 匿名——我們說匿名,是因爲它不像普通的方法那樣有一個明確的名稱:寫得少而想
得多!
 函數——我們說它是函數,是因爲Lambda函數不像方法那樣屬於某個特定的類。但和方
法一樣,Lambda有參數列表、函數主體、返回類型,還可能有可以拋出的異常列表。
 傳遞——Lambda表達式可以作爲參數傳遞給方法或存儲在變量中。
 簡潔——無需像匿名類那樣寫很多模板代碼。

Lambda語法測驗

根據上述語法規則,以下哪個不是有效的Lambda表達式?

(1) () -> {}
(2) () -> “Raoul”
(3) () -> {return “Mario”;}
(4) (Integer i) -> return “Alan” + i;
(5) (String s) -> {“IronMan”;}

答案:只有4和5是無效的Lambda。
(1) 這個Lambda沒有參數,並返回 void 。它類似於主體爲空的方法: public void run() {} 。
(2) 這個Lambda沒有參數,並返回 String 作爲表達式。
(3) 這個Lambda沒有參數,並返回 String (利用顯式返回語句)。
(4) return 是 一 個 控 制 流 語 句 。 要 使 此 Lambda 有 效 , 需 要 使 花 括 號 , 如 下 所 示 :
(Integer i) -> {return “Alan” + i;} 。
(5)“Iron Man”是一個表達式,不是一個語句。要使此Lambda有效,你可以去除花括號和分號,如下所示:
(String s) -> “Iron Man” 。或者如果你喜歡,可以使用顯式返回語句,如下所示:
(String s)->{return “IronMan”;} 。

函數式接口

定義

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

函數式接口測驗

下面哪些接口是函數式接口?

public interface Adder{
int add(int a, int b);
}
public interface SmartAdder extends Adder{
int add(double a, double b);
}
public interface Nothing{
}

答案:只有 Adder 是函數式接口。
SmartAdder 不是函數式接口,因爲它定義了兩個叫作 add 的抽象方法(其中一個是從Adder 那裏繼承來的)。
Nothing 也不是函數式接口,因爲它沒有聲明抽象方法。

在哪裏可以使用Lambda?

以下哪些是使用Lambda表達式的有效方式?

(1) execute(() -> {});
public void execute(Runnable r){
r.run();
}
(2)
public Callable fetch() {
return () -> “Tricky example ;-)”;
}
(3) Predicate p = (Apple a) -> a.getWeight();

答案:只有1和2是有效的。
第一個例子有效,是因爲Lambda () -> {} 具有簽名 () -> void ,這和 Runnable 中的
抽象方法 run 的簽名相匹配。請注意,此代碼運行後什麼都不會做,因爲Lambda是空的!
第 二 個 例 子 也 是 有 效 的 。 事 實 上 , fetch 方 法 的 返 回 類 型 是 Callable 。
Callable 基本上就定義了一個方法,簽名是 () -> String ,其中 T 被 String 代替
了。因爲Lambda () -> “Trickyexample;-)” 的簽名是 () -> String ,所以在這個上下文
中可以使用Lambda。
第三個例子無效,因爲Lambda表達式 (Apple a) -> a.getWeight() 的簽名是 (Apple) ->
Integer ,這和 Predicate:(Apple) -> boolean 中定義的 test 方法的簽名不同。

public class FunATest {
    public static void main(String[] args) {


        FunATest funATest = new FunATest();

        //Java8寫法
        funATest.execute(() -> { });//也可以什麼都不做 畢竟function interface 是Runnable

        funATest.execute(() -> { System.out.printf("A1");System.out.println("A2"); });//多行必須加上{}

        funATest.execute(() -> System.out.println("B1"));//單行可以省略{}
        /*其實 () -> { }就是下面runnable後面的代碼,可以看到確實省略了很多呢!*/

        //中正的做法
        Runnable runnable = () -> {
            System.out.println("run = [" + "Runnable" + "]");
        };
        funATest.execute(runnable);

        //以前的寫法
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("runnable1.run");
            }
        };
        funATest.execute(runnable1);
    }

    public void execute(Runnable r) {
        new Thread(r).start();
    }
}

函數式接口@FunctionalInterface:
函數式接口定義且只定義了一個抽象method
函數式接口的抽象方法的簽名稱爲函數描
述符。所以爲了應用不同的Lambda表達式,你需要一套能夠描述常見函數描述符的函數式接口。

Java API中已經有了幾個函數式接口

     Predicate<T>——接收T對象並返回boolean
     Consumer<T>——接收T對象,不返回值
     Function<T, R>——接收T對象,返回R對象
     Supplier<T>——提供T對象(例如工廠),不接收值
     naryOperator<T>——接收T對象,返回T對象
     inaryOperator<T>——接收兩個T對象,返回T對象

下面的code對幾個函數式接口依次舉例說明,最後還會對一些特殊函數式接口單獨舉例說明(如Function

public class FunctionTestA {
    public static void main(String[] args) {
        isDoubleBinaryOperator();
    }

    /**
     * DoubleBinaryOperator double applyAsDouble(double left, double right)
     */
    public static void isDoubleBinaryOperator(){
        DoubleBinaryOperator doubleBinaryOperatorA = (double a,double b) ->  a+b;
        DoubleBinaryOperator doubleBinaryOperatorB = (double a,double b) ->  a-b;
        System.out.println(doubleBinaryOperatorA.applyAsDouble(StrictMath.random()*100,StrictMath.random()*100));
        System.out.println(doubleBinaryOperatorB.applyAsDouble(StrictMath.random()*100,StrictMath.random()*100));
        /**
         * 像類似地DoubleBinaryOperator這樣的函數式接口還有很多它們都是被FunctionalInterface註解的函數式接口
         * 被FunctionalInterface註解過的interface必須符合FunctionalInterface規範
         * IntBinaryOperator,LongBinaryOperator等都和BinaryOperator相似
         */
    }

    /**
     * BinaryOperator<T>——接收兩個T對象,返回T對象
     */
    public static void isBinaryOperator(){
        BinaryOperator<StringBuilder> binaryOperator = (StringBuilder builder1,StringBuilder builder2) -> {
            builder1.append(builder2);return builder1;
        };
    }

    /**
     * UnaryOperator<T>——接收T對象,返回T對象
     */
    public static void isUnaryOperator(){
        UnaryOperator<User> unaryOperator = (User user) -> {user.setId(4);user.setUsername("alice");return user;};
        User user = unaryOperator.apply(new User());
        System.out.println(user);
    }

    /**
     * Supplier<T>——提供T對象(例如工廠),不接收值
     */
    public static void isSupplier(){
        Supplier<List<User>> supplier = () -> Collections.synchronizedList(new ArrayList<User>());
        List<User> userList = supplier.get();
        userList.add(new User("Blake",5));userList.add(new User("Alice",4));
        System.out.println(userList);
    }

    /**
     * Function<T, R>——接收T對象,返回R對象
     */
    public static void isFunction(){
        String s ="Many other students choose to attend the class, although they will not get any credit. ";
        Function<String,String[]> stringFunction = (String str) -> {return str.split("[^\\w]");};
        String[] strings = stringFunction.apply(s);
        for (String s1:strings) System.out.println(s1);

        Function stream = (S) -> {return new Object();};//奇怪的語法
        Object o = stream.apply("hello");
        System.out.println(o.getClass());
    }

    /**
     * Consumer<T>——接收T對象,不返回值
     */
    public static void isConsumer(){
        Consumer<List> listConsumer = (List list) -> {
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) System.out.println(iterator.next());
        };

        List<String> list = new ArrayList<>(Arrays.asList("Alice","BOb"));
        listConsumer.accept(list);
    }

    /**
     * Predicate<T>——接收T對象並返回boolean
     */
    public static void isPredicate(){
        Predicate<String> predicate = (String s) -> { return s!=null;};
        System.out.println("判斷是否爲Null:"+predicate.test(null));

        Predicate<Integer> integerPredicate = (Integer a) -> {return (a>10);};
        System.out.println(integerPredicate.test(8));

        Predicate<String[]> predicateStrings = (String...strs) -> {return strs.length >= 3;};
        System.out.println(predicateStrings.test(new String[]{"","",""}));
    }
}

上面對一些函數式接口做了簡單的說明,現在看下源碼

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }


    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

可以看到都被@FunctionInterface註解 註解過,因此當我們查看oracle官方手冊發現,我們是可以自定義函數式接口的
在定義函數式接口時要注意必須是interface然後是必須是一個method並且是abstract的
現在隨便定義一些函數式接口

/**
 * Created by zhou on 18-1-17.
 * 自定義函數接口 FunA
 */
@FunctionalInterface
public interface FunA {
    public int add(int a, int b);
}
/**
 * Created by zhou on 18-1-17.
 * 自定義函數接口 FunB
 */
@FunctionalInterface
public interface FunB {
    public String value(String...strings);
}
/**
 * Created by zhou on 18-1-17.
 * 自定義函數接口FunC
 */
@FunctionalInterface
public interface FunC {
    public void print(String...strings);
}

然後我們在來看一些如何使用

 //FunA Lambda表達式
  FunA funA = (int a, int b) -> a + b;
  System.out.println(funA.add(3, 5));

  //FunB Lambda
  String[] strings = {"h", "e", "l", "l", "o"};
  FunB funB = (String... strs) -> {//多行
      StringBuilder builder = new StringBuilder(1024);
      for (String s : strs) builder.append(s);
      return builder.toString();
  };
  System.out.println(funB.value(strings));

  //FunC Lambda
  FunC funC = (String... sts) -> System.out.println(Arrays.toString(sts));
  funC.print("Inspired by a can of tea given to him by one of his Chinese friends in 2004,".split("[^\\w]"));

  Runnable runnable = () -> System.out.println("一個線程!");
  new Thread(runnable).start();

  Predicate<Runnable> predicate = (Runnable r) -> r != null;
  System.out.println(predicate.test(runnable) ? "is not Null" : "is Null");

對單個函數式接口的說明

BinaryOperator<T>——接收兩個T對象,返回T對象

UnaryOperator<T>——接收T對象,返回T對象

Function<T, R>——接收T對象,返回R對象

首先Function

/**
     * 主要用來表現一些數學思想
     */
    public static void isFunction() {
        /*下面三者的寫法雖然不同,但是思路都完全一致,可以看作Y->X->Z這樣一步一步簡化而來*/
        //f(x) = x+1
        Function<Integer, Integer> fun1Z = x -> x + 1;//標記Z
        Function<Integer, Integer> fun1X = (Integer x) -> x + 1;//標記X
        Function<Integer, Integer> fun1Y = (Integer x) -> { return x + 1; }; //標記Y

        Function<Integer, Integer> funX = x -> x * 2;
        Function<Integer, Integer> funY = x -> (x * 2) * x + 1;


        //f(x) = x*2 + 1 ==>說明:原本是f(x)=x+1 compose()設x*2 = x代入就得到了f(x) = x*2 + 1 這裏要注意的是type 必須一致
        //f1(x) = x+1 , f2(x) = x*2 複合 f1(x) = f2(x) + 1;
        Function<Integer, Integer> fun1 = fun1X.compose(funX);
        System.out.println("(5*2)+1=" + fun1.apply(5));//(5*2)+1
        System.out.println("(6*2)+1=" + fun1.apply(6));//(6*2)+1

        //Function還有一個method andThen
        /*f(x) = x+1 和 f(x) = (x*2)*x+1這兩個函數,
        那麼andThen的用法是:當前誰調用誰就先執行執行的結果作爲參數(或者數學上說的未知數X)傳入andThen(fun)中fun的函數中去執行
        因此執行順序就是fun1Y先執行,得到結果後作爲X的值然後funY進行運算
        f(x) = 3+1 ==> x =4 ==>f(x) = (4*2)*4+1=33
        f(x) =((x+1)*2)*(x+1)+1
        */
        fun1 = fun1Y.andThen(funY);
        System.out.println("f(x) =((x+1)*2)*(x+1)+1 ==>((3+1)*2)*(3+1)+1=" + fun1.apply(3));


        //f(x) = x*x , f(x) = x*x*x
        Function<Integer, Long> fun2A = x -> (long) x * x;
        Function<Double, Double> fun2B = x -> x * x * x;
        System.out.println("x*x ==> 4*4=" + fun2A.apply(4) + " ");
    }

打印結果:

(5*2)+1=11
(6*2)+1=13
f(x) =((x+1)*2)*(x+1)+1 ==>((3+1)*2)*(3+1)+1=33
x*x ==> 4*4=16 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章