Map Interface in Java With Example

The Map Interface is the mapping between a key and a value i.e. it contains values based on the key. Each key value pair is often known as an entry, As Map contains only unique keys, we can also say Map interface maps unique keys to its corresponding values. With the key we can retrieve a value when we require later.

Important Note: The Map interface do not Extends the Collection interface


Map Implementations

1. HashMap

HashMap is a class that implements Map Interface and Extends AbstractMap class. HashMap stores our data in a pair such that each element has a key associated with it.

It is generally denoted as HashMap <key, value> or HashMap <K,V>.

Example of HashMap Implementation :

Let us discuss HashMap Implementation with the help of program, following program has been divided into 4 Steps that we will discuss one by one.

import java.util.*;
public class HashMapDemoClass{

public static void main(String args[]){

//Step 1: Object of HashMap is Created
HashMap<Integer,String> HashMap=new HashMap<Integer,String>();  

//Step 2: Data is entered using Put() method
HashMap.put(1001,"India");    
HashMap.put(1002,"Canada");
HashMap.put(1003,"Australia");

 //Step 3: Used for Each loop to iterate
for(Map.Entry map  :  HashMap.entrySet() ) 

{
//Step 4: used getKey() and getValue() methods
System.out.println(map.getKey()+" "+map.getValue());   
}
}
}

Output:

1001 India

1002 Canada

1003 Australia

Description of Example:

  • In Step 1, we have created an object of HashMap collection, As we have already discussed HashMap has key value pair, so obviously we have to define the type of key and value, We have defined Key of Integer type, and Value of String type.
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have used For Each loop to retrieve the values from the HashMap. We have used method entrySet() which returns the Set containing all the keys and values
  • In Step 4 we have used two methods , First is getKey() , which as name suggest retrieves the key and secondly getValue() method that retrieves the values corresponding to the keys.

For more read HashMap tutorial

2. LinkedHashMap

LinkedHashMap is a type of Collection, which takes all the functionalities of HashMap class i.e. it stores our data in a pair such that each element has a key associated with it. As, HashMap does not maintains the insertion order, that is when we retrieve values from it we do not get that values in the same order we have entered in it. So, The functionality of maintaining the insertion is added into LinkedHashMap. To attain this  functionality all the entries(key and value) are linked to each other using doubly-linked list. This doubly-linked list maintains the iteration ordering, which is in general the order in which keys were added in  the map.

Example of LinkedHashMap Implementation :

Let us discuss LinkedHashMap Implementation with the help of program, following program has been divided into 4 Steps that we will discuss one by one. 

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {
public static void main(String[] args) {

//Step 1: linkedHashMap object is created
Map<String, Integer> linkedHashMapobject = new LinkedHashMap<String, Integer>();
//Step 2: Elements are entered using put() method
linkedHashMapobject.put("Samsung Grand quattro price ", new Integer(10000));
linkedHashMapobject.put("Micromax canvas price", new Integer(9000));
linkedHashMapobject.put("Sony T2 Ultra price", new Integer(20000));
linkedHashMapobject.put("Nokia Lumia price", new Integer(15000));
linkedHashMapobject.put("Microsoft Lumia price ", new Integer(16000));

//Step 3: printing contents of linkedhashMap
System.out.println("Contents of LinkedHashMap : " + linkedHashMapobject);
 
System.out.println("\nValues of linkedHashMapobject after iterating over it : \n");

//Step 4: using for each loop to iterate over linkedHashMap
for (String key : linkedHashMapobject.keySet()) {                                              
System.out.println(key + “:\t” + linkedHashMapobject.get(key));
}
}
}

Output:

Contents of LinkedHashMap : {Samsung Grand uattro price =10000, Micromax canvas price=9000, Sony T2 Ultra price=20000, Nokia Lumia price=15000, Microsoft Lumia price =16000}
 
Values of linkedHashMapobject after iterating over it :

Samsung Grand uattro price :    10000

Micromax canvas price:           9000

Sony T2 Ultra price:             20000

Nokia Lumia price:               15000

Microsoft Lumia price :          16000

Description of Example:

  • In Step 1, we are creating an object linkedHashMap object that is storing key of String type and value of Integer type
  • In Step 2, we are using put method to add the key value pair in the object we have created in step 1.
  • In Step 3 we are printing  the contents of the LinkedHashMap
  • In Step 4 we are using for each loop to iterate over the linkedhashmap object , we are using keySet and get(key) method to diplay all the values of map, we will discuss each method in detail in next topic.

For more details read LinkedHashMap tutorial

3. TreeMap

TreeMap also stores values based on the corresponding key. It stores only unique keys, that is duplicate keys are not allowed. Also it cannot store key as null but it can store null values. It is mostly similar to HashMap except it maintains natural order of keys. If key is of integer type it arranges them in increasing order, or if they are of string type, it arranges them in dictionary order.

Example of TreeMap Implementation :

Let us discuss TreeMap Implementation with the help of program, following program has been divided into 4 Steps that we will discuss one by one.

 
import java.util.*;

public class TreeMapDemo{

public static void main(String args[]){

 //Step 1: object of TreeMap is created
TreeMap<Integer,String> treemap=new TreeMap<Integer,String>();  

//Step 2: Elements are entered using put() method
treemap.put(102,"Core");  
treemap.put(100,"I");
treemap.put(103,"Java");
treemap.put(101,"Love");

//Step 3: used for each loop to iterate over Map
for(Map.Entry map  : treemap.entrySet()){  
//Step 4: used getKey() and getValue() method
System.out.println(map.getKey()+" "+map.getValue());  

}
}
}

Output:

100 I

101 Love

102 Core

103 Java

In output,We have obtained output in ascending order based on the Key, which distinguishes it from hash map

Description of Example:

  • In Step 1, we have created an object of Tree Map collection, We have defined key of Integer type and value of String type.
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have used For Each loop to retrieve the values from the Tree Map. We have used method entrySet() which returns the Set containing all the keys and values.
  • In Step 4 we have used two methods , First is getKey () , which as name suggest retrieves the key and secondly getValue () method that retrieves the values corresponding to the keys.

For more details read TreeMap tutorial


Map Methods

1. void clear( )

This method Removes all entries from the  map object.

2. boolean containsKey(Object k)

This method returns true if the given map contains k as a key else it returns false.

3. boolean containsValue(Object v)

This method returns true if the given map contains v as a value else it returns false

4. Set entrySet( )

This method returns a Set that contains the entries in the map. This method provides a set view of the invoking map object.

5. boolean equals(Object obj)

This method returns true if obj is a Map that contains the same entries in the calling map object else it returns false.

6. Object get(Object k)

This method returns the value associated with the key k.

7. int hashCode( )

This method returns the hash code for the invoking map.

8. boolean isEmpty( )

This method returns true if the invoking map object is empty else it returns false.

9. Set keySet( )

This method returns a Set that contains the keys in the invoking map. This method provides a set view of the keys in the calling map.

10. Object put(Object k, Object v)

This method puts an entry in the calling map that overwrites any previous value associated with the key, if associated.

11. void putAll(Map m)

This method puts all the entries from Map m into the calling map.

12. Object remove(Object k)

This method removes the entry whose key equals k.

13. int size( )

This method returns the number of entries in the map.

14. Collection values( )

This method Returns a collection that contains the values in the map. This method returns a collection view of the values in the map.


Map Important Points In JAVA

  • Map has three implementation classes HashMap, LinkedHashMap and TreeMap. If we have requirement of storing elements in natural order than we should use TreeMap and if we have requirement of retrieving the elements as it is entered than we should use LinkedHashMap, and if no such requirements are there we can use HashMap.
  • Duplicate keys are not allowed.
  • Key value pair is known as Entry
  • The Map interface do not Extends the Collectioninterface
  • We cannot Iterate over the Entries of the map using Iterator or ListIterator.

Map Interface Quick Revision Points

  • Duplicates keys are not allowed
  • TreeMap is preferred where we want to store data in natural order
  • LinkedHashMap is preferred where we want to maintain insertion order.
  • HashMap is preferred where we just want to store data without any requirement of maintaining any special ordering
  • It is not part of collection Interface