Java8學習筆記(一)--Lambda表達式

兩個概念

函數式接口

函數式接口就是隻顯式聲明一個抽象方法的接口。爲保證方法數量很少很多,java8提供了一個專用註解@FunctionalInterface,這樣,當接口中聲明的抽象方法多於或少於一個時就會報錯。以下圖所示:

java

Lambda表達式

Lambda表達式本質上是一個匿名方法。讓咱們來看下面這個例子:ide

public int add(int x, int y) {
    return x + y;
}

轉成Lambda表達式後是這個樣子:函數

(int x, int y) -> x + y;

參數類型也能夠省略,Java編譯器會根據上下文推斷出來:測試

(x, y) -> x + y; //返回兩數之和

或者this

(x, y) -> { return x + y; } //顯式指明返回值

可見Lambda表達式有三部分組成:參數列表,箭頭(->),以及一個表達式或語句塊。code

Lambda表達式和函數式接口結合

步驟:blog

  1. 新建無參函數式接口(先演示無參);
  2. 新建包含屬性爲函數式接口的類;
  3. 實現函數式接口;
  4. 測試函數式接口的方法;

新建無參函數式接口

@FunctionalInterface
public interface InterfaceWithNoParam {
    void run();
}

新建包含屬性爲函數式接口的類

public class TestJava8{
InterfaceWithNoParam param;
}

實現函數式接口

public class TestJava8{
    //匿名內部類
    InterfaceWithNoParam param1 = new InterfaceWithNoParam() {
        @Override
        public void run() {
            System.out.println("經過匿名內部類實現run()");
        }
    };
    //Lambda表達式
            //空括號表示無參
    InterfaceWithNoParam param = () -> System.out.println("經過Lambda表達式實現run()") ;
}

測試函數式接口的方法

@Test
public void testIntfaceWithNoparam() {

    this.param.run();
    this.param1.run();
}

運行結果

其餘形式的函數式接口及實現

上述內容實現了無參無返回值的函數接口與實現,固然還有其餘形式:接口

  1. 有參無返回值
  2. 無參有返回值
  3. 有參有返回值

有參無返回值

接口

@FunctionalInterface
public interface InterfaceWithParams {
    void run(String s);
}

實現

InterfaceWithParams params = new InterfaceWithParams() {
    @Override
    public void run(String s) {
        System.out.println("經過" + s + "實現run(String)");
    }
};
InterfaceWithParams params1 = (String s) -> System.out.println("經過" + s + "實現run(String)");

測試

this.params.run("匿名類");
    this.params1.run("Lambda");

運行

無參有返回值

接口

@FunctionalInterface
public interface InterfaceUnVoidWithNoParam {
    String run();
}

實現

InterfaceUnVoidWithNoParam interfaceUnVoidWithNoParam = new InterfaceUnVoidWithNoParam() {
    @Override
    public String run() {
        return "Hello World!";
    }
};
InterfaceUnVoidWithNoParam interfaceUnVoidWithNoParam1 = () -> "Hello Lambda!";

測試

String s = this.interfaceUnVoidWithNoParam.run();
    System.out.println("返回結果是:"+s);
    String s0 = this.interfaceUnVoidWithNoParam1.run();
    System.out.println("返回結果是:"+s0);

運行

有參有返回值

接口

@FunctionalInterface
public interface InterfaceUnVoidWithParams {
    String run(Integer integer);
}

實現

InterfaceUnVoidWithParams interfaceWithParams = new InterfaceUnVoidWithParams() {
    @Override
    public String run(Integer integer) {
        return String.valueOf(integer);
    }
};
InterfaceUnVoidWithParams interfaceWithParams1 = (Integer integer) -> String.valueOf(integer);

測試

String s1 = this.interfaceWithParams.run(1);
    System.out.println("您輸入的是:"+s1);
    String s2 = this.interfaceWithParams1.run(2);
    System.out.println("您輸入的是:"+s2);

運行

相關文章
相關標籤/搜索