当前位置: 博客首页>> 学习笔记 >> 阅读正文

初始化HashMap并初始化值

作者: 分类: 学习笔记 发布于: 2023-05-16 10:38:52 浏览:1,262 评论(0)


有几种方法可以初始化HashMap并初始化值:

方法1:使用put方法

Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("a", 1);
hashMap.put("b", 2);
hashMap.put("c", 3);

方法2:使用静态代码块

Map<String, Integer> hashMap = new HashMap<String, Integer>() {{
    put("a", 1);
    put("b", 2);
    put("c", 3);
}};

方法3:使用Java 9中的Map.of()方法

Map<String, Integer> hashMap = Map.of("a", 1, "b", 2, "c", 3);

方法4:使用Java 8中的Stream API

Map<String, Integer> hashMap = Stream.of(new Object[][]{
        {"a", 1},
        {"b", 2},
        {"c", 3}
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
       

转载时请注明出处及相应链接。

本文永久链接: https://blog.baigei.com/articles/hashmap-init