Collections and Generics
Maps
HashMap and TreeMap classes
The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.
There are two classes that implement the Map interface: HashMap and TreeMap.
An introduction to maps
- A map is a collection that contains values that are associated with keys.
- A map consists of entries, with each entry divided into two parts: key and values. No duplicate keys are allowed in the map. Both key and value can be an instance of any class.
- The main advantage of a map is its performance in locating an entry, given the key.
- The main difference between a hash map and a tree map is that a tree map automatically maintains entries in order based on the key values.
- If an application doesn't require that the entries be kept in order, a hash map is often more efficient than a tree map.
The HashMap and TreeMap classes
java.util.HashMap java.util.TreeMap
The HashMap and TreeMap classes are two concrete implementations of the Map interface. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.
Common constructors of the HashMap and TreeMap classes
Constructor | Description |
---|---|
HashMap | Creates an empty HashMap using the specified types for the keys and values. |
TreeMap | 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 the entries in the map as Map.Entry objects. |
get(key) | Returns the value for the entry with the specified key. Returns null if the key isn't 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) | Removes the entry with the specified key. |
size() | Returns the number of entries in the map. |
To traverse a map, you must first call its entrySet method to get a set of elements. The method returns an instance of a class that implements the Set interface, another interface in JCF, that models a mathematical set.
Common methods of the Map.Entry interface
Method | Description |
---|---|
getKey() | Returns the key for the map entry. |
getValue() | Returns the value for the map entry. |
Each entry of a map implements the Map.Entry interface in the java.util.Map package. You can use two of the Map.Entry methods to get the key and value for an entry.