1.
Map Interface
A map is an object that stores associations between keys and values, or key/value
pairs.
Given a key, you can find its value.
Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, like the HashMap and
LinkedHashMap, but some do not like the TreeMap.
The [Link] interface represents a mapping between a key and a value.
Map is generic and is declared as shown here: interface Map<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
Few characteristics of the Map Interface are:
1. A Map cannot contain duplicate keys and each key can map to at most one value.
Some implementations allow null key and null value like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on specific implementations,
e.g TreeMap and LinkedHashMap have predictable order, while HashMap does not.
3. There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, TreeMap and LinkedHashMap.
Why and When to use Maps?
Maps are perfect to use for key-value association mapping such as dictionaries.
The maps are used to perform lookups by keys or when someone wants to retrieve
and update elements by keys. Some examples are:
o A map of error codes and their descriptions.
o A map of zip codes and cities.
o A map of managers and employees. Each manager (key) is associated with a
list of employees (value) he manages.
o A map of classes and students. Each class (key) is associated with a list of
students (value).
Maps revolve around two basic operations: get( ) and put( ). To put a value into a
map, use put( ), specifying the key and the value. To obtain a value, call get( ),
passing the key as an argument. The value is returned.
To do this, you can use the entrySet( ) method. It returns a Set that contains the
elements in the map.
To obtain a collection-view of the keys use keySet( ).
To get a collection-view of the values, use values( ).
Collection-views are the means by which maps are integrated into the larger
Collections Framework.
Write a JAVA program to demonstrate working of Map Interface
import [Link].*;
class HashMapDemo
{
public static void main(String args[])
{
Map< String,Integer> hm = new HashMap< String,Integer>();
[Link]("a", new Integer(100));
[Link]("b", new Integer(200));
[Link]("c", new Integer(300));
[Link]("d", new Integer(400));
// Returns Set view
Set< [Link]< String,Integer> > st = [Link]();
for ([Link]< String,Integer> me:st)
{
[Link]([Link]()+":");
[Link]([Link]());
}
}
}
Output:
a:100
b:200
c:300
d:400
4. The HashMap Class
The HashMap class extends AbstractMap and implements the Map interface. It
uses a hash table to store the map. This allows the execution time of get( ) and
put( ) to remain constant even for large sets.
HashMap is a generic class that has this declaration: class HashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
The following constructors are defined:
HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
The first form constructs a default hash map. The second form initializes the hash
map by using the elements of m. The third form initializes the capacity of the
hash map to capacity. The fourth form initializes both the capacity and fill ratio
of the hash map by using its arguments. The meaning of capacity and fill ratio
is the same as for HashSet, described earlier. The default capacity is 16. The
default fill ratio is 0.75.
HashMap implements Map and extends AbstractMap. It does not add any
methods of its own.
Output from this program is shown here (the precise order may vary):
The program begins by creating a hash map and then adds the mapping of
names to balances. Next, the contents of the map are displayed by using a
set- view, obtained by calling entrySet( ). The keys and values are displayed by
calling the getKey( ) and getValue( ) methods that are defined by [Link].
Pay close attention to how the deposit is made into John Doe’s account. The
put( ) method automatically replaces any preexisting value that is associated
with the specified key with the new value. Thus, after John Doe’s account is
updated, the hash map will still contain just one "John Doe" account.
5. The LinkedHashMap Class
LinkedHashMap extends HashMap. It maintains a linked list of the entries in
the map, in the order in which they were inserted. This allows insertion-
order iteration over the map. That is, when iterating through a collection-
view of a LinkedHashMap, the elements will be returned in the order in
which they were inserted. You can also create a LinkedHashMap that
returns its elements in the order in which they were last accessed.
LinkedHashMap is a generic class that has this declaration:class
LinkedHashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
LinkedHashMap defines the following constructors:
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)
The first form constructs a default LinkedHashMap. The second form initializes
the LinkedHashMap with the elements from m. The third form initializes the
capacity. The fourth form initializes both capacity and fill ratio. The meaning
of capacity and fill ratio are the same as for HashMap. The default capacity is
16. The default ratio is 0.75. The last form allows you to specify whether the
elements will be stored in the linked list by insertion order, or by order of last
access. If Order is true, then access order is used. If Order is false, then insertion
order is used.
LinkedHashMap adds only one method to those defined by HashMap. This
method is removeEldestEntry( ), and it is shown here:
protected boolean removeEldestEntry([Link]<K, V> e)
This method is called by put( ) and putAll( ). The oldest entry is passed in e.
By default, this method returns false and does nothing.
However, if you override this method, then you can have the
LinkedHashMap remove the oldest entry in the map. To do this, have your
override return true. To keep the oldest entry, return false.
6. Hashtable
The Hashtable class implements a hash table, which maps keys to values. Any non-
null object can be used as a key or as a value. To successfully store and retrieve
objects from a hashtable, the objects used as keys must implement the hashCode
method and the equals method.
The [Link] class is a class in Java that provides a key-value data
structure, similar to the Map interface.
Example program:
Output
Value of A: 1
Key: A, Value: 1
Key: C, Value: 3
Features of Hashtable
It is similar to HashMap, but is synchronized.
Hashtable stores key/value pair in hash table.
In Hashtable we specify an object that is used as a key, and the value we want
to associate to that key. The key is then hashed, and the resulting hash code is
used as the index at which the value is stored within the table.
The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-
fast Enumeration.
Declaration: public class Hashtable<K,V> extends Dictionary<K,V> implements
Map<K,V>, Cloneable, Serializable
Type Parameters:
K – the type of keys maintained by this map
V – the type of mapped value
7. The TreeMap Class
The TreeMap class extends AbstractMap and implements the NavigableMap
interface. It creates maps stored in a tree structure.
A TreeMap provides an efficient means of storing key/value pairs in sorted
order and allows rapid retrieval. You should note that, unlike a hash map, a
tree map guarantees that its elements will be sorted in ascending key order.
TreeMap is a generic class that has this declaration: class TreeMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
The following TreeMap constructors are defined:
TreeMap( )
TreeMap(Comparator<? super K> comp)
TreeMap(Map<? extends K, ? extends V> m)
TreeMap(SortedMap<K, ? extends V> sm)
The first form constructs an empty tree map that will be sorted by using
the natural order of its keys. The second form constructs an empty tree-
based map that will be sorted by using the Comparator comp. (Comparators
are discussed later in this chapter.) The third form initializes a tree map with
the entries from m, which will be sorted by using the natural order of the
keys. The fourth form initializes a tree map with the entries from sm, which
will be sorted in the same order as sm.
TreeMap has no map methods beyond those specified by the NavigableMap
interface and the AbstractMap class.
The following program reworks the preceding example so that it uses TreeMap:
The following is the output from this program: