在Java中,可以使用以下几种方法初始化一个Map并给其赋值:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
Map<String, Integer> map = new HashMap<String, Integer>(){{
put("key1", 1);
put("key2", 2);
}};
Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
Map<String, Integer> map = Map.ofEntries(
entry("key1", 1),
entry("key2", 2)
);
无论使用哪种方法,都可以初始化一个Map并给其赋值。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java怎么初始化map并赋值