How do I create a dictionary in Java?

27,880

Solution 1

Java uses HashMaps instead of dictionaries.

Some other Maps include TreeMap. The difference is in the backend (one uses a hash table, the other uses a Red-Black tree)

Example:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
....

Map<String,String> mMap = new HashMap<String, String>();
mMap.put("key", "something");
Iterator iter = mMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry mEntry = (Map.Entry) iter.next();
    System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}

Solution 2

Generally you can use HashMap like so:

Map<String, String> map = new HashMap<String, String>();

For example, now you could use this map object much like you would a dictionary in Python.

map.put("Key", "Value");
System.out.println(map.get("Key"));

There are several other classes that implement the Map interface that are useful for utilizing a Dictionary in Java (some are better to use in certain situations than others).

Solution 3

Possible alternative for Dictionary in Java is HashMap. You can refer to Oracle's Documentation for Further References. http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Solution 4

You can check

http://docs.oracle.com/javase/6/docs/api/java/util/Map.html

If you're concerned about performance, you should try TreeMap. I assume that you care more about retrieval time than insertion one.

Solution 5

A word may contains more than one meaning. so you can use MultiMap.

    MultiMap dictionary = new MultiValueMap();
    dictionary.put("key", "something");
    dictionary.put("key", "Important");
    System.out.println("dictionary Value : "+dictionary.get("key"));

dictionary Value : [something, Important]

Share:
27,880
BarnyardOwl
Author by

BarnyardOwl

Updated on July 09, 2022

Comments

  • BarnyardOwl
    BarnyardOwl almost 2 years

    I am curious as to how to create a dictionary in Java. I know that Python had a dictionary setup similar to dictionary = {"key": "something"}. I know there are other ways to do this in Java, such as creating two synchronized lists and using the same position in each list to mimic a dictionary.

    ArrayList<Object> keys = new ArrayList<Object>();
    ArrayList<Object> values = new ArrayList<Object>();
    public void add(Object key, Object value){
        keys.add(key);
        values.add(value);
    }
    // And a subsequent return function
    public Object getValue(Object key) {
        return values.get(keys.indexOf(key));
    }
    

    However, this screams to me bad programming. Is there a simpler syntax to do it with a single statement? Most questions already asked about the subject are closed and, consequently, of little help.