Java程序使用Lambda表达式初始化HashMap
要使用Lambda初始化HashMap,请首先创建一个HashMpa并使用Callable-
HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>()
对于键值对,您需要通过以下方式对其进行初始化-
HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
{
put(0, () -> {
return 10;
});
put(1, () -> {
return 20;
});
}
};示例
import java.util.HashMap;
import java.util.concurrent.Callable;
public class Demo {
public static void main(String[] args) throws Exception {
HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>>() {
{
put(0, () -> {
return 10;
});
put(1, () -> {
return 20;
});
put(2, () -> {
return 30;
});
put(3, () -> {
return 40;
});
}};
System.out.println(map.get(0).call());
System.out.println(map.get(1).call());
System.out.println(map.get(2).call());
System.out.println(map.get(3).call());
}
}
}输出结果
10 20 30 40
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短