如何实现 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
广告