For Java Version 9 or higher: (对于Java版本9或更高版本:)
Yes, this is possible now. (是的,现在有可能。) In Java 9 a couple of factory methods have been added that simplify the creation of maps : (在Java 9中,添加了一些工厂方法,这些方法可简化地图的创建:)
// this works for up to 10 elements:
Map<String, String> test1 = Map.of(
"a", "b",
"c", "d"
);
// this works for any number of elements:
Map<String, String> test2 = Map.ofEntries(
entry("a", "b"),
entry("c", "d")
);
In the example above both test
and test2
will be the same, just with different ways of expressing the Map. (在上面的示例中, test
和test2
都是相同的,只是表达Map的方式不同。) The Map.of
method is defined for up to ten elements in the map, while the Map.ofEntries
method will have no such limit. (Map.of
方法最多可为地图中的十个元素定义,而Map.ofEntries
方法将没有此限制。)
Note that in this case the resulting map will be an immutable map. (请注意,在这种情况下,生成的地图将是不可变的地图。) If you want the map to be mutable, you could copy it again, eg using mutableMap = new HashMap<>(Map.of("a", "b"));
(如果您希望地图可变,则可以再次复制它,例如,使用mutableMap = new HashMap<>(Map.of("a", "b"));
)
(See also JEP 269 and the Javadoc ) ((另请参见JEP 269和Javadoc ))
For up to Java Version 8: (对于Java版本8:)
No, you will have to add all the elements manually. (不,您将必须手动添加所有元素。) You can use an initializer in an anonymous subclass to make the syntax a little bit shorter: (您可以在匿名子类中使用初始化程序,以使语法短一些:)
Map<String, String> myMap = new HashMap<String, String>() {{
put("a", "b");
put("c", "d");
}};
However, the anonymous subclass might introduce unwanted behavior in some cases. (但是,在某些情况下,匿名子类可能会引入不需要的行为。) This includes for example: (例如,这包括:)
- It generates an additional class which increases memory consumption, disk space consumption and startup-time (它会生成一个附加类,从而增加内存消耗,磁盘空间消耗和启动时间)
- In case of a non-static method: It holds a reference to the object the creating method was called upon. (对于非静态方法:它包含对创建方法所调用的对象的引用。) That means the object of the outer class cannot be garbage collected while the created map object is still referenced, thus blocking additional memory (这意味着在仍然引用创建的map对象的同时,无法对外部类的对象进行垃圾回收,从而阻塞了额外的内存)
Using a function for initialization will also enable you to generate a map in an initializer, but avoids nasty side-effects: (使用函数进行初始化还将使您能够在初始化器中生成映射,但避免了讨厌的副作用:)
Map<String, String> myMap = createMap();
private static Map<String, String> createMap() {
Map<String,String> myMap = new HashMap<String,String>();
myMap.put("a", "b");
myMap.put("c", "d");
return myMap;
}