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


兩個概念

函數式接口

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

Lambda表達式

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

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

轉成Lambda表達式后是這個樣子:

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

參數類型也可以省略,Java編譯器會根據上下文推斷出來:

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

或者

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

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

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

步驟:

  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);

運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM