传统方式
# 传统方式
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
private static final Map<String, String> myMap = new HashMap<>();
static {
myMap.put("key1", "value1");
myMap.put("key2", "value2");
}
java8新特性-双括号初始化
# java8新特性-双括号初始化
Map<String, String> map1 = new HashMap<>() {{
put("k1", "v1");
put("k2", "v2");
}};
# 慎用 非静态内部类/匿名内部类包含了外围实例的引用,如果拥有比外部类更长的生命周期,有内存泄露隐患
private static final HashMap<String, String> myMap1 = new HashMap<>() {{
put("key1", "value1");
put("key2", "value2");
}};
java9新特性-最简便的方式
# java9新特性-最简便的方式
Map<String, String> map2 = Map.of("k1", "v1", "k2", "v2");
# 不可变集合
private static final Map<String, String> myMap20 = Map.of();
private static final Map<String, String> myMap2 = Map.of("kye1", "value1", "key2", "value2");
private static final Map<String, String> myMap21 = Map.of("kye1", "value1", "key2", "value2","kye3", "value1","kye4", "value1","kye5", "value1","kye6", "value1","kye7", "value1","kye8", "value1","kye9", "value10","kye10", "value1");
com.google.guava提供的方法
# com.google.guava提供的方法
Map<String, String> myMap3 = ImmutableMap.of("kye1", "value1", "key2", "value2");
Map<String, String> myMap4 = ImmutableMap.<String, String>builder().put("kye1", "value1").put("key2", "value2").build();
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
参考
Java Map初始化的几种方法
Map用法总结
文章出处登录后可见!
已经登录?立即刷新