java 更好的地图构造器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6833925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better Map Constructor
提问by Ben Noland
Is there a more streamlined way to do the following?
是否有更简化的方法来执行以下操作?
Map<String, String> map = new HashMap<String, String>();
map.put("a", "apple");
map.put("b", "bear");
map.put("c", "cat");
I'm looking for something closer to this.
我正在寻找更接近于此的东西。
Map<String, String> map = MapBuilder.build("a", "apple", "b", "bear", "c", "cat");
回答by Nathan Hughes
There's always double-brace initialization:
总是有双括号初始化:
Map<String, String> map = new HashMap<String, String>(){{
put("a", "apple"); put("b", "bear"); put("c", "cat");}};
There are problems with this approach. It returns an anonymous inner class extending HashMap, not a HashMap. If you need to serialize the map then know that serialization of inner classes is discouraged.
这种方法存在问题。它返回一个扩展 HashMap 的匿名内部类,而不是一个 HashMap。如果您需要序列化映射然后知道不鼓励内部类的序列化。
回答by Maurício Linhares
No, there isn't, but I wrote a method to do exactly this, inspired by Objective-C NSDictionary class:
不,没有,但我写了一个方法来做到这一点,灵感来自 Objective-C NSDictionary 类:
public static Map<String, Object> mapWithKeysAndObjects(Object... objects) {
if (objects.length % 2 != 0) {
throw new IllegalArgumentException(
"The array has to be of an even size - size is "
+ objects.length);
}
Map<String, Object> values = new HashMap<String, Object>();
for (int x = 0; x < objects.length; x+=2) {
values.put((String) objects[x], objects[x + 1]);
}
return values;
}
回答by Eugene Kuleshov
You could use ImmutableMap.Builderfrom Google collections library.
您可以使用Google 集合库中的ImmutableMap.Builder。
回答by Aleksandr Dubinsky
Java 9adds Map.of
, such as:
Java 9添加了Map.of
,例如:
Map<String, String> map = Map.of("a", "apple", "b", "bear", "c", "cat");
Up to 10 entries are supported. For more entries you can use the overload taking Entry:
最多支持 10 个条目。对于更多条目,您可以使用重载获取条目:
Map<String, String> map
= Map.ofEntries
(Map.entry("a", "apple")
, Map.entry("b", "bear")
, Map.entry("c", "cat"));
Note that these methods do not return a HashMap. It returns an optimized immutable map.
请注意,这些方法不返回 HashMap。它返回一个优化的不可变映射。
回答by whirlwin
You could always use double brace initialization:
你总是可以使用双括号初始化:
Map<String, String> map = new HashMap<String, String>() {{
put("foo", "bar");
put("baz", "qux");
}}
But bear in mind this might not be efficient according to these answers.
但请记住,根据这些答案,这可能效率不高。