传统方式
# 传统方式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用法总结