How do you create a dictionary in Java?

user1849819 picture user1849819 · Nov 24, 2012 · Viewed 559.1k times · Source

I am trying to implement a dictionary (as in the physical book). I have a list of words and their meanings.

What data structure / type does Java provide to store a list of words and their meanings as key/value pairs.

How, given a key, can I find and return the value?

Answer

arshajii picture arshajii · Nov 24, 2012

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap is probably the most common; the go-to default.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal