CodingBison

A Map interface is one of the widely used Collection interfaces. Unlike other collection interfaces, Map interface does not extend Collection Interface. In other words, Collection interface is "not" the root of Map interface.



Figure: Collection Framework Map Interfaces and Classes

A Map is an object that stores key/value pairs. Both key and value are objects, and they can be same or different objects. In fact, they can even be "Null". However, there is one important constraint -- each "key" in the Map object can at most relate/map/correspond to one "value". In other words, a Map does not allow duplicate keys.

Things To Remember
Map does not allow duplicate Keys.

There are quite a few classes that implement Map interface, but we will discuss only few of them in this module: HashMap, LinkedHashMap, SortedMap, NavigableMap, and TreeMap. As shown in the figure above, LinkedHashMap is a sub-class of HashMap and HashMap extends the Map interface. This concept of Key/Value pair is similar to HashTable/Hash Functions. The behavior of HashMap and LinkedHashMap is analogous to that of HashSet and LinkedHashSet that are discussed in detail in the Set interface. The above figure also shows another sequence of inheritance: SortedMap extends Map, NavigableMap extends SortedMap, and TreeMap implements NavigableMap.

We also recommend that the reader should go through the Hash Functions/Hash Tables section of data structures modules, before getting into the details of Map interface.

Methods defined in Map interface

Map interfaces offers a long list of methods. The table below list all the methods that deal with insertion, retrieval, and deletion aspects of the Map.


Table: GET/PUT/REMOVE Methods of Map Interface
MethodDescription
Object put(Object K, Object V)Inserts value V for key K into the Map. The key K is used to retrieve the value V from the map. The method put() returns "null" if the value V for a Key K does not exist in the Map. If there is a Value V associated with the Key K, the put() method returns the old value V and it is replaced with the new value V. A map M is said to contain a mapping for a key K if and only if m.containsKey(K) returns true
Object putIfAbsent(Object K, Object V)Inserts value V for key K into the Map. Insertions of (K,V) pair happens only if it is absent. Unlike, put() method, this methods does not replace the old value. A map M is said to contain a mapping for a key K if and only if m.containsKey(K) returns true
void putAll(Map M)Copies all the associations of the map M into the "map object" that calls this method.
Object get(Object K)Returns the value V associated with the key K. Returns "null" if there is no value associated with the key K.
Set<k> entrySet()Returns all the Values of the "map object" that calls this method.
Set<k> keySet()Returns all the Keys of the "map object" that calls this method.
Object remove(Object K)Returns and removes value V associated with the key K. Returns "null" if there is no value associated with the key K.
bool remove(Object K, Value v)Removes value V associated with the key K, only if it already has the (key,Value) association in the Map.
void clear()Removes all associations from the "map object" that calls this method.
Object replace(Object k, Object V)Replaces the entry for the specified Key, only if currently mapped to some value.
Object replace(Object k, Object vOld, Object vNew)Replaces the entry for the specified Key, only if currently mapped to some "vOld".

With that, let us see an example to understand the usage of the above mentioned operations. The example uses HashMap class to demonstrate the usage of the methods defined by the Map interface. As shown in the Figure at the top of this page, HashMap is one of the Classes that implements the Map interface.

 import java.util.HashMap;
 import java.util.Map;

 public class MapDemo {
     public static void main(String[] args) {
        Map mobj = new HashMap();

        mobj.put(1237,"John");
        mobj.put(2013,"Ray");
        mobj.put(1024,"Mike");
        int key = 1237;
        System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
        System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
        System.out.println(" All map keys " + mobj.keySet());
        System.out.println(" All map Elements " + mobj);

        mobj.remove(1237);
        System.out.println(" All map Elements " + mobj);
    }
 }

Notice the above example program and you would notice that a Map always stores the Key/Value pairs. In the above example, 1237, 2013, 1024 are all keys and the names "John", "Ray", "Mike" are Values. For example, the sample set provided above could treated like the information of all employees in an organization. An Employee ID is the Key and Employee Name is the Value. Every employee has an Unique ID and the employee information is retrieved using the ID.

Let us Compile/run the program, Here is the output:

  Key: 1237, Name: John
  Value associated with key: John
  All map keys [1237, 1024, 2013]
  All map Elements {1237=John2, 1024=Mike, 2013=Ray}
  All map Elements {1024=Mike, 2013=Ray}

Map interface methods continues.

In addition to the insertion, retrieval and deletion methods defined above, the Map interface also packs additional methods that are very handy. We list them in the table below.


Table: Generic Methods of Map Interface
MethodDescription
int size()Returns the size of the Map.
Set entrySet()Returns the set View of the Map.
Collection values()Returns all the values of the Map (in Collection view).
bool isEmpty()Returns "True" if the Map is empty. Returns "False" otherwise.
bool containsKey(Object K)Returns True if the map contains a Value mapped for the key object K. Returns False otherwise.
bool containsValue(Object V)Returns True if the map contains a (Key,Value) mapping for the Value V. Returns False otherwise. Its kind of opposite to what "containsKey" does.

Our next (rather simple) example demonstrates the method that are present in the above table. So, here we go!

 import java.util.HashMap;
 import java.util.Map;

 public class MapDemo2 {
     public static void main(String[] args) {
         Map mobj = new HashMap();

         mobj.put(1237,"John");
         mobj.put(2013,"Ray");
         mobj.put(1024,"Mike");

         System.out.println(" All map Elements " + mobj);
         System.out.println(" Set View of the map: " + mobj.entrySet());
         System.out.println(" Collection View of the map: " + mobj.values());
         System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
         System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
         System.out.println(" Map Size : " + mobj.size());
     }
 }

Let us go ahead and compile/run the program. Here is the output:

  All map Elements {1237=John, 1024=Mike, 2013=Ray}
  Set View of the map: [1237=John, 1024=Mike, 2013=Ray]
  Collection View of the map: [John, Mike, Ray]
  Contains Key ? : false
  Contains Value ? : true
  Map Size : 3




comments powered by Disqus