初始化空Map
- 常规方法
Map<String, String> map = new HashMap<>();
- 使用guava库
Map<String, String> map = ImmutableMap.of();
需要引入maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.3-jre</version>
</dependency>
初始化非空Map
- 常规方法
Map<String, String> map = new HashMap<>();
map.put("a", "A");
map.put("b", "B");
map.put("c", "C");
- 使用guava库
Map<String, String> map = ImmutableMap.of("a", "A", "b", "B", "c", "C");
需要引入maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.3-jre</version>
</dependency>
- 使用 {{ }}
Map<String, String> map = new HashMap(){{
put("a","A");
put("b","B");
}};