Java 中 HashMap 的字面声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32333652/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:02:14  来源:igfitidea点击:

Literal declaration of HashMap in Java

javahashmapliterals

提问by Shahid Thaika

In JavaScript, you can declare all the keys and value combinations for a JSONobject in one go as follows...

在 中JavaScript,您可以JSON一次性声明一个对象的所有键和值组合,如下所示...

var myJSON = {
    'key1' : 'value 1',
    'key2' : 'value 2',
    'key3' : 'value 3',
    'key4' : 'value 4',
    'key5' : 'value 5',
    'key6' : 'value 6'
};

I was wondering whether we can do something similar in Javafor HashMaps.

我想知道我们是否可以在Javafor 中做类似的事情HashMaps

HashMap<String, String> map = new HashMap<String, String>(
    "Key 1", "Value 1",
    "Key 2", "Value 2",
    "Key 3", "Value 3"
);

Basically, I need this as a one time read only thing as Config for the other parts of my code. I searched and tried a few solutions, but was not able to make them work. Or is there a better approach that I can do?

基本上,我需要将它作为一次性只读的东西作为我代码其他部分的配置。我搜索并尝试了一些解决方案,但无法使它们起作用。或者有没有更好的方法我可以做?

回答by Suresh Atta

Though {{(double brace) is an anti pattern, something like this you can write

虽然{{(双括号)是一种反模式,但你可以这样写

HashMap<String, String> map = new HashMap<String, String>(){{
put("Key 1", "Value 1");
put("Key 2", "Value 2");
put("Key 3", "Value 3");    
}};

Edit :

编辑 :

If you are looking for a better way to put elements, iterate over your json and put key values in a loop.

如果您正在寻找一种更好的方法来放置元素,请遍历您的 json 并将键值放入循环中。

回答by assylias

There is no concept of map literals in Java but you can easily write a utility method to achieve something similar. See this implementationfor example. You can then initialise a map (using static imports):

Java 中没有映射字面量的概念,但您可以轻松编写一个实用程序方法来实现类似的功能。例如,请参阅此实现。然后您可以初始化地图(使用静态导入):

Map<String, String> map = map("k1", "v1", "k2", "v2");

An alternative is to use the "double brace initialisation" syntax but it creates an anonymous inner class which is not necessarily a good idea.

另一种方法是使用“双括号初始化”语法,但它创建了一个匿名内部类,这不一定是一个好主意。