1. 程式人生 > >Lamdba表示式和函式表示式(一)

Lamdba表示式和函式表示式(一)

Lamdba想必很多人都知道,但是實際上很少有人真的能用起來,其實這個功能還是很方便的,在我們日常開發中都是很實用的。

條件,要求jdk的版本是 8.0或者更高的版本,現在jdk9.0都出來了,這個功能我們必須要掌握,方便我們的開發,減少了程式碼量

一般形式

(這裡寫引數) -> {這裡寫函式體}

當然如果引數和函式體很少,就可以不寫外面的區域符號,例如persion -> "100"這個看不懂沒關係,我只是說明下有這種情況

1, 我們自己定義一個藉口,然後製作一個函式式介面

    @FunctionalInterface
    interface WrapUser{
       void
insert(User user); }

2,定義一個User類,這個就不多說了

3,使用:

  User user = new User("hongbiao", 25);
        WrapUser wu  = User -> System.out.print(user.getName()+"--"+user.getAge());
        wu.insert(user);

解釋下,這段程式碼,第一行是建立一個物件,第二行是例項化這個介面,例項化這個介面就要實現這個接口裡面的所有抽象的方法,返回的是一個介面物件 wu, 最後一步就是呼叫這個接口裡面的方法。
主要是第二句 User表示的是需要的引數型別,-> 後面的是函式體,因為這裡只有一句話所以省略了花括號,也可以這樣寫
WrapUser wu = (User) -> {System.out.print(user.getName()+"--"+user.getAge());};

函式體內呼叫方法

(這裡寫引數) -> {function()}

1, 首先要確認介面中是否有返回值,如果有返回值,這單獨函式體內必須有返回值,沒有返回值會報錯,如果介面中沒有返回值,這在函式體內無論有沒有返回值都可以。

2,例項

介面,無返回值

    @FunctionalInterface
    interface WrapUser{
       void insert(User user);
    }

有返回值的方法和無返回值的方法

    static void delet(){
        System.out.print("delete---"
); } static int add(){ System.out.print("delete---"); return 1; }

使用,這樣一來,lamdba表示式呼叫函式,無論函式是否有返回值都不報錯

        User user = new User("hongbiao", 25);
        WrapUser wu  = User ->  System.out.print(user.getName()+"--"+user.getAge());
        wu.insert(user);
        WrapUser wu2  = User ->  delet();
        wu.insert(user);
        WrapUser wu3  = User ->  add();
        wu.insert(user);

介面,有返回值 此時的介面是一個有返回值的介面

    @FunctionalInterface
    interface MapSet{
        int get();
    }

有返回值和無返回值的方法

    static int getAge(){
        return 25;
    }
    static void delet(){
        System.out.print("delete---");
    }

使用 這裡寫程式碼片

        MapSet map = () -> 100;
        map.get();

        MapSet map2 = () -> getAge();
        map.get();
        /**
         * 介面中需要返回值,而delete這個函式沒有返回值,因此報錯
         */
        MapSet map3 = () -> delet(); //這裡是報錯的
        map.get();

這裡寫圖片描述

函式式介面,以上所說的各種lamdba,是不是所有的介面都可以這樣寫呢,當然不是,所謂的函數語言程式設計是指一個有且只有一個抽象方法的介面,當然 用default和static修飾的方法除外,這兩個關鍵字是java8 裡面的新特性,例如我們看一下系統介面Runable這個介面,在介面上一行使用@FunctionalInterface註解表明這是一個函式式介面,那麼我們就可以使用lamdba表示式來寫。

package java.lang;

/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Runable使用函式表示式

        //不使用函式表示式
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print("hello biaoge");
            }
        }).start();
        //使用函式表示式
        new Thread(()->System.out.print("hello biaoge")).start();

從上面來看,函式表示式明顯方便簡潔