Java HashMap associative multi dimensional array can not create or add elements
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
if (!myArray.containsKey("en")) {
myArray.put("en", new HashMap<String, String>());
}
myArray.get("en").put("name", "english name");
In Java you have to be explicit about when you are creating an object. In this case first we check if there is already a HashMap
object stored in our outer HashMap
under the key "en". If not, we create an empty one.
Now to put a new value into it we have to first get it from the outer HashMap
, then put the new value.
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> value = new HashMap<String, String>();
value.put("name", "English name");
value.put("desc", "English description");
value.put("keys", "English keywords");
myArray.put("en" , value);
value = new HashMap<String, String>();
value.put("name", "French name");
value.put("desc", "French description");
value.put("keys", "French keywords");
myArray.put("fr" , value);
Unfortunately, there's no concise syntax for constructing populated maps in Java. You'll have to write it out long-hand. A separate helper method can make it a little simpler:
HashMap<String, String> makeMap(String name, String desc, String keys) {
HashMap<String, String> map = new HashMap<>();
// Before Java 7, above must be: new HashMap<String, String>();
map.put("name", name);
map.put("desc", desc);
map.put("keys", keys);
}
Then:
HashMap<String, HashMap<String, String>> myArray = new HashMap<>();
myArray.put("en",
makeMap("english name", "english description", "english keywords"));
// etc.
You would retrieve it with:
english_name = myArray.get("en").get("name");