如何實現 IntFunction用 Java 中的 lambda 表示式?


IntFunction 介面是 Java 8 中的函式式 介面,在java.util.function 包中定義的。該介面接受一個整數值引數作為輸入,並返回一個型別為R的值。IntFunction介面可以用作lambda 表示式方法引用的賦值目標,並且僅包含一個抽象方法apply()

語法

@FunctionalInterface
public interface IntFunction<R> {
   R apply(int value);
}

示例

import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;

public class IntFunctionTest {
   public static void main(String[] args) {
      IntFunction<String> getMonthName = monthNo -> {  // lambda expression
         Map<Integer, String> months = new HashMap<>();
         months.put(1, "January");
         months.put(2, "February");
         months.put(3, "March");
         months.put(4, "April");
         months.put(5, "May");
         months.put(6, "June");
         months.put(7, "July");
         months.put(8, "August");
         months.put(9, "September");
         months.put(10, "October");
         months.put(11, "November");
         months.put(12, "December");
         if(months.get(monthNo)!= null) {
            return months.get(monthNo);
         } else {
            return "The number must between 1 to 12";
         }
      };
      int input = 1;
      String month = getMonthName.apply(input);
      System.out.println("Month number "+ input +" is: "+ month);
      input = 10;
      System.out.println("Month number "+ input +" is: "+ getMonthName.apply(input));
      input = 15;
      System.out.println("Month number "+ input +" is: "+ getMonthName.apply(input));
   }
}

輸出

Month number 1 is: January
Month number 10 is: October
Month number 15 is: The number must between 1 to 12

更新日期:2020-07-13

390 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.