Java 8 - Lambda

Lambda是Java8中的新特性,用來在Java中實(shí)現(xiàn)函數(shù)式編程。


Lambda

0.什么是Lambda

Lambda表達(dá)式是一段可以傳遞的代碼。
將面向?qū)ο笾袀鬟f數(shù)據(jù)編程傳遞行為。
如果原來是這樣編寫一個線程:

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("do something");
    }
}

Runnable接口中只有一個run()方法,當(dāng)把Runnable對象給Thread對象作為構(gòu)造參數(shù)時創(chuàng)建一個線程,運(yùn)行后輸出"do something",上面的例子用匿名內(nèi)部類實(shí)現(xiàn)了這個方法。
這是一個“代碼即數(shù)據(jù)”的例子,在run方法中是線程要執(zhí)行的一個任務(wù),但是上面的代碼中任務(wù)內(nèi)容已經(jīng)被規(guī)定死了。當(dāng)我們有多個任務(wù)的時候,需要多次重復(fù)編寫上述代碼。

用Lambda表達(dá)式實(shí)現(xiàn)起來是這樣的,簡便很多:

Runnable r = () -> System.out.println("do something");

1. 基本語法

Lambda表達(dá)式基本樣式為:

expression = (variable) -> action
  • variable:變量,也可以是給占位符
  • action:實(shí)現(xiàn)的代碼邏輯部分,可以是一行代碼也可以是一個代碼片段。
    Lambda表達(dá)式特征有:
  • 可選類型說明:不需要聲明類型,編譯器統(tǒng)一識別參數(shù)值
  • 可選參數(shù)小括號:一個參數(shù)無需定義小括號,但是多個參數(shù)還是需要
  • 可選的大括號如果主體只包含了一個語句,就不需要使用大括號
  • 可選的返回關(guān)鍵字(return):如果主體只有一個表達(dá)式返回值則編譯器會自動返回該值,大括號則需要指定返回值。

2.Lambda表達(dá)式實(shí)例

package com.junzerg.test;

public class LambdaTest {
    public static void main(String args[]) {
        LambdaTest tester = new LambdaTest();
        
        // 類型聲明
        MathOperation addition = (int a, int b) -> a + b;
        // 不用類型聲明
        MathOperation subtraction = (a, b) -> a - b;
        // 大括號中的返回語句
        MathOperation multiplication = (int a, int b) -> {return a * b;};
        // 沒有大括號以及返回語句
        MathOperation division = (int a, int b) -> a / b;
        
         System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
         System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
         System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
         System.out.println("10 / 5 = " + tester.operate(10, 5, division));
         
         // 不用括號
         GreetingService greetService1 = message -> System.out.println("Hello " + message);
         // 用括號
         GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
         
         greetService1.sayMessage("Runoob");
         greetService2.sayMessage("Google");
    }

    interface MathOperation{
        int operation(int a, int b);
    }
    
    interface GreetingService{
        void sayMessage(String message);
    }
    
    private int operate(int a, int b, MathOperation mathOperation) {
        return mathOperation.operation(a, b);
    }
}

3.變量作用域

3.1 final修飾的域外局部變量

Lambda表達(dá)式只能引用標(biāo)記了final的外層局部變量,也就是說不能再lambda表達(dá)式內(nèi)部修改定義在域外的局部變量。
以下代碼正常輸出:

public class Java8Tester {
 
   final static String salutation = "Hello! ";
   
   public static void main(String args[]){
      GreetingService greetService1 = message -> 
      System.out.println(salutation + message);
      greetService1.sayMessage("Runoob");
   }
    
   interface GreetingService {
      void sayMessage(String message);
   }
}

3.2 final修飾的外部局部變量

以下代碼正常輸出:

public class Java8Tester {
    public static void main(String args[]) {
        final int num = 1;
        Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
        s.convert(2);  // 輸出結(jié)果為 3
    }
 
    public interface Converter<T1, T2> {
        void convert(int i);
    }
}

3.3 不用final修飾的局部變量

lambda表達(dá)式的局部變量也可以不聲明為final,但是絕不可以被后面的代碼修改(即隱形的具有final的語義)。
以下代碼不能通過編譯:

int num = 1;  
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5;  
//報錯信息:Local variable num defined in an enclosing scope must be final or effectively final

3.4 局部變量

在Lambda表達(dá)式中不允許聲明一個與局部變量同名的參數(shù)或者局部變量。
以下代碼不能通過編譯:

String first = "";  
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());  //編譯會出錯 

5. lambda表達(dá)式的常見實(shí)例

5.1 函數(shù)式接口

函數(shù)式接口是只有一個方法的接口,用作lambda表達(dá)式的類型。例如之前的Runnable的例子。
下面是一個函數(shù)式接口:
@FunctionalInterface注解表明這是一個函數(shù)是接口,也就是說這個函數(shù)只有一個抽象方法。

public class FunctionalInterfaceDemo {
  @FunctionalInterface
  interface Predicate<T> {
    boolean test(T t);
  }
  /**
  * 執(zhí)行Predicate判斷
  * @param age       年齡
  * @param predicate Predicate函數(shù)式接口
  * @return          返回布爾類型結(jié)果
  */
  public static boolean doPredicate(int age, Predicate<Integer> predicate) {
    return predicate.test(age);
  }

  public static void main(String[] args) {
    boolean isAdult = doPredicate(20, x -> x >= 18);
    System.out.println(isAdult);
  }
}

這樣可以很方便的完成判斷是否是成人的動作。

5.2 Java 8中的function包

實(shí)際上在Java 8中提供了一個function包作為這種例子的使用寶典。
function包中的接口大致分為一下幾類:

接口 參數(shù) 返回值 類別 示例
Consumer T void 消費(fèi)型接口 輸出一個值
Supplier None T 供給型接口 工廠方法
Function T R 函數(shù)型接口 獲得Artist對象的名字
Predicate T boolean 斷言型接口 這張唱片已經(jīng)發(fā)行了么
消費(fèi)型接口示例
public static void donation(Integer money, Consumer<Integer> consumer){
    consumer.accept(money);  
}
public static void main(String[] args) {
    donation(1000, money -> System.out.println("好心的麥樂迪為Blade捐贈了"+money+"元")) ;
}
供給型接口示例
public static List<Integer> supply(Integer num, Supplier<Integer> supplier){
       List<Integer> resultList = new ArrayList<Integer>()   ;
       for(int x=0;x<num;x++)  
           resultList.add(supplier.get());
       return resultList ;
}
public static void main(String[] args) {
    List<Integer> list = supply(10,() -> (int)(Math.random()*100));
    list.forEach(System.out::println);
}
函數(shù)型接口示例

轉(zhuǎn)換字符串為Integer

public static Integer convert(String str, Function<String, Integer> function) {
    return function.apply(str);
}
public static void main(String[] args) {
    Integer value = convert("28", x -> Integer.parseInt(x));
}
斷言型接口示例

篩選出只有兩個字的水果:

public static List<String> filter(List<String> fruit, Predicate<String> predicate){
    List<String> f = new ArrayList<>();
    for (String s : fruit) {
        if(predicate.test(s)){
            f.add(s);
        }
    }
    return f;
}
public static void main(String[] args) {
    List<String> fruit = Arrays.asList("香蕉", "哈密瓜", "榴蓮", "火龍果", "水蜜桃");
    List<String> newFruit = filter(fruit, (f) -> f.length() == 2);
    System.out.println(newFruit);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容