Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and assign the values to a hashMap directly

Tags:

java

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.

like image 830
user3197309 Avatar asked Dec 02 '22 20:12

user3197309


2 Answers

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

HashMap<String,String> instruments = new HashMap<String, String>() {
{
        put("test","test");
        put("test1","test1");
}
};
like image 82
Santhosh Kumar Vijayarangan Avatar answered Mar 05 '23 14:03

Santhosh Kumar Vijayarangan


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

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

But I wouldn't recommend it.

like image 40
Mathias Lavaert Avatar answered Mar 05 '23 15:03

Mathias Lavaert