Markuss Baumgarts Markuss Baumgarts - 10 months ago 44
Python Question

How to create a dictionary in java, similar to the ones in python?

I am working on a text based game in java and would like to use a python like dictionary for the map, the HashMap doesn't really work for me since i want to have multiple values linked to the one dictionary e.g.

In python you can define a dictionary like this:

room_x = { "name": "X",

"description":"Random description",

"exits": {linked to another dictionary},

"items": list_of_players_items}

Is something similar possible in Java?

Thanks in advance.

Answer Source

HashMap can do the work:

HashMap<String, String> hashMap = new HashMap<>();  //<key,value>  both key and value are Strings
hashMap.put("name", "X");
hashMap.put("description", "Random description");

To link multiple values. you need to change the key value pair types as

HashMap<String,HashMap<String, String>> linkedMap = new HashMap<>();  // key is string and value is HashMap<String, String>
HashMap<String,String> itemsMap = new HashMap<>();
itemsMap.put("item1", "this is first item");
itemsMap.put("item2", "this is second item");
linkedMap.put("items", itemsMap);

Above code is just a quick example I wrote, you need to declare the real type of your data, it doesn't have to be String.
Hope it helps.