How to work with maps

The associated package for HashMap and TreeMap classes:

  • java.util.HashMap
  • java.util.TreeMap

Common constructors of the HashMap and TreeMap classes:

Constructors Description
HashMap<K,V>() Creates an empty HashMap using the specified types for the keys and values.
TreeMap<K,V>() Creates an empty TreeMap using the specified types for the keys and values.

Common methods of the HashMap and TreeMap classes:

Method Description
clear() Removes all entries from the map.
containsKey(key) Returns true if the specified key is in the map.
containsValue(value) Returns true if the specified value is in the map.
entrySet() Returns a set of all entries in the map as Map.Entry objects.
get(key) Returns the value for the entry with the secified key. Returns ull if the key is not found.
put(key, value) Adds an entry with the specified key and value, or replaces the value if an entry with the key already exists.
remove(key, value) Removes the entry with the specified key.
size() Returns the number of entries in the map.

Common mehtods of the Map.Entry interface:

Method Description
getKey() Returns the key for the map entry.
getValue() Returns the value for the map entry.

Descriptions:

  • A map is a collection that contains values that are associated with keys. The two most commonly used classes that implement maps are HashMap and TreeMap.
  • The main difference between HashMap and TreeMap automaticlly maintains entryies in order based on the key values. If an application doesn't require that the entries be kept in order, a HashMap is often more efficient than a TreeMap.
  • Each entry of a map implements the Map.Entry interface in the java.util.Map package. You can use two of the methods provided by this interface to get the key and value for an entry.

Note:

  • You can use a custom class for the key objects of a HashMap. To do that, the class must override the hashCode and equals methods inherited from Object.

Example 1: Code that uses a hash map

// create an empty hash map
HashMap<String, String> books = new HashMap<String, String>();
// Add the entries
books.put( "wooz", "Wizard of Oz");
books.put( "mbdk", "Mobby Dick");
books.put( "wuth", "War and Peace");
// print the entries.
for (Map.Entry book : books.entrySet())
System.out.println(book.getKey() + ": " + book.getValue());
// print the entry whose key is "mbdk"
System.out.println("\nCode mbk is " + books.get("mbk"));

Example 2: Code that uses a tree map

// create an empty tree map
TreeMap<String, String> books = new TreeMap<String, String>();
// Add the entries
books.put( "wooz", "Wizard of Oz");
books.put( "mbdk", "Mobby Dick");
books.put( "wuth", "War and Peace");
// print the entries.
for (Map.Entry book : books.entrySet())
System.out.println(book.getKey() + ": " + book.getValue());
// print the entry whose key is "mbdk"
System.out.println("\nCode mbk is " + books.get("mbk"));