Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal declaration of HashMap in Java [duplicate]

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

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 Java for 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?

like image 717
Shahid Thaika Avatar asked Sep 01 '15 14:09

Shahid Thaika


People also ask

Does HashMap allow duplicate values in Java?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do I find duplicates in a HashMap?

How To Find Duplicate Elements In Array In Java Using HashMap? In this method, We use HashMap to find duplicates in array in java. We store the elements of input array as keys of the HashMap and their occurrences as values of the HashMap. If the value of any key is more than one (>1) then that key is duplicate element.

What happens if we enter duplicate key in map in Java?

As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.


2 Answers

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.

like image 149
Suresh Atta Avatar answered Nov 03 '22 12:11

Suresh Atta


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

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.

like image 25
assylias Avatar answered Nov 03 '22 14:11

assylias