在Java中如何用lambda表达式实现IntFunction?
IntFunction接口是Java8中的函数接口,定义在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 表达式
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: JanuaryMonth number 10 is: OctoberMonth number 15 is: The number must between 1 to 12
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短