1. 程式人生 > 其它 >常用的函式式介面之Supplier介面

常用的函式式介面之Supplier介面

Supplier<T>:包含一個無參的方法

T get():獲得結果

該方法不需要引數,它會按照某種實現邏輯(由Lambda表示式實現)返回一個數據

Supplier<T>也被稱為生產型介面,如果我們指定了介面的泛型是什麼型別,那麼介面中的get方法就會生產什麼型別的資料供我們使用

import java.util.function.Supplier;

public class SupplierDemo {
  public static void main(String[] args) {
      //呼叫 getInt方法
      Integer i = getInt(() -> 123);//Lambda表示式簡寫版
      System.out.println(i);        

  }
  //定義一個方法,用來接收get返回的資料
  private static Integer getInt(Supplier<Integer> sl){
      return sl.get();
  }
}

練習:

定義一個類,提供getMax方法用於返回一個數組中的最大值並呼叫

package Demo0512;

import java.util.function.Supplier;

public class SupplierDemo01 {
  public static void main(String[] args) {
      //宣告一個數組
      int array[] = {12, 45, 4, 87, 546, 54};
      //呼叫
      int max1 = getMax(() -> {
          int max = array[0];
          for (int i = 0; i < array.length; i++) {
              if (max < array[i]) {
                  max = array[i];
              }
          }
          return max;
      });
      System.out.println(max1);
  }
  private static int getMax(Supplier<Integer> sl) {
      return sl.get();
  }
}