问题
我需要初始化一个常量HashMap,并希望在一行语句中完成它。像这样避免......
hashMap.put("One", new Integer(1)); // adding value into HashMap
hashMap.put("Two", new Integer(2));
hashMap.put("Three", new Integer(3));
在目标C中类似于此:
[NSDictionary dictionaryWithObjectsAndKeys:
@"w",[NSNumber numberWithInt:1],
@"K",[NSNumber numberWithInt:2],
@"e",[NSNumber numberWithInt:4],
@"z",[NSNumber numberWithInt:5],
@"l",[NSNumber numberWithInt:6],
nil]
我没有找到任何一个显示如何做到这一点的例子看了这么多。
#1 热门回答(182 赞)
你可以这样做:
Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
put("One", 1);
put("Two", 2);
put("Three", 3);
}};
#2 热门回答(48 赞)
你可以使用Google Guava的ImmutableMap。只要你不关心稍后修改Map(在使用此方法构造它之后无法在 Map 上调用.put()),这就可以正常工作:
import com.google.common.collect.ImmutableMap;
// For up to five entries, use .of()
Map<String, Integer> littleMap = ImmutableMap.of(
"One", Integer.valueOf(1),
"Two", Integer.valueOf(2),
"Three", Integer.valueOf(3)
);
// For more than five entries, use .builder()
Map<String, Integer> bigMap = ImmutableMap.<String, Integer>builder()
.put("One", Integer.valueOf(1))
.put("Two", Integer.valueOf(2))
.put("Three", Integer.valueOf(3))
.put("Four", Integer.valueOf(4))
.put("Five", Integer.valueOf(5))
.put("Six", Integer.valueOf(6))
.build();
参见:http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html
一个有点相关的问题:ImmutableMap.of() workaround for HashMap in Maps?
#3 热门回答(24 赞)
在Java 9中,可以使用Map.of(...)
,如下所示:
Map<String, Integer> immutableMap = Map.of("One", 1, "Two", 2, "Three", 3);
这个 Map 是不可变的。如果你希望 Map 是可变的,则必须添加:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
如果你不能使用Java 9,那么你将自己编写类似的帮助方法或使用第三方库(如Guava)为你添加该功能。