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?
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With