Java中初始化Map并赋值有多种方式,具体取决于使用的Map实现类。以下是几种常用的方式:
使用HashMap初始化并赋值:Map<String, Integer> map = new HashMap<>();map.put("key1", 1);map.put("key2", 2);
使用LinkedHashMap初始化并赋值:Map<String, Integer> map = new LinkedHashMap<>();map.put("key1", 1);map.put("key2", 2);
使用TreeMap初始化并赋值:Map<String, Integer> map = new TreeMap<>();map.put("key1", 1);map.put("key2", 2);
使用Map.of方法初始化并赋值(适用于Java 9及以上版本):Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
使用Map.entry方法初始化并赋值(适用于Java 8及以上版本):Map<String, Integer> map = new HashMap<>();map.putAll(Map.ofEntries(Map.entry("key1", 1),Map.entry("key2", 2)));
注意:上述示例中的数据类型可以根据实际情况进行更改。