Java 如何直接将值声明和分配给 hashMap

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

How to declare and assign the values to a hashMap directly

java

提问by user3197309

Like String s="sample" in java.How to declare and assign values to a hashMap in one step. Also is it possible to assign more set of values at a time using put function in hashMap.

就像java中的String s="sample"一样。如何一步一步地对hashMap进行声明和赋值。也可以使用 hashMap 中的 put 函数一次分配更多组值。

回答by Mathias Lavaert

Use a library like Google Guava which has lots of utilities to instantiate HashMaps. It is also possible doing anonymous inheritance like this:

使用像 Google Guava 这样的库,它有很多实用程序来实例化 HashMaps。也可以像这样进行匿名继承:

    Map<String, Object> map = new HashMap<String, Object>() {{
        put("Test", "Test1");
        put("Test", "Test1");
    }};

But I wouldn't recommend it.

但我不会推荐它。

回答by injecteer

such constructs do not exist in good ol' java.

这种结构在好的 ol' java 中不存在。

On one hand, you can use property files formatfor that. You can save your map as a something-separated key-value pairs in a string or a file, and read them in a loop filling your map with each pair.

一方面,您可以使用property files format它。您可以将您的地图保存为字符串或文件中的一些分隔键值对,并在循环中读取它们,用每一对填充您的地图。

on the other hand, if you really need that + possible type-checking, you can look at modern dynamic JVM languages, like Groovyor Scala.

另一方面,如果你真的需要那个 + 可能的类型检查,你可以看看现代动态 JVM 语言,比如GroovyScala

there you can use the code as it is:

在那里您可以按原样使用代码:

def map = [ a:1, b:23, c:"aasdasd" ]

回答by Santhosh K Vijayan

Yes, it is possible. you can use the below code

对的,这是可能的。你可以使用下面的代码

HashMap<String,String> instruments = new HashMap<String, String>() {
{
        put("test","test");
        put("test1","test1");
}
};