如何實現 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP