Map Interface in Java

The Map interface present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. A map contains unique keys.

Map Interface in Java

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of Map interface
  
import java.util.*;
class HashMapDemo {
    public static void main(String args[])
    {
        Map<String, Integer> hm
            = new HashMap<String, Integer>();
  
        hm.put("a", new Integer(100));
        hm.put("b", new Integer(200));
        hm.put("c", new Integer(300));
        hm.put("d", new Integer(400));
  
        // Returns Set view
        Set<Map.Entry<String, Integer> > st
            = hm.entrySet();
  
        for (Map.Entry<String, Integer> me : st) {
            System.out.print(me.getKey() + ":");
            System.out.println(me.getValue());
        }
    }
}

chevron_right


Output:

a:100
b:200
c:300
d:400

Performing various operations using Map Interface and HashMap Class

Since Map is an interface, it can be used only with a class that implements this interface. Now, let’s see how to perform a few frequently used operations on a Map using the widely used HashMap class. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the map.



1. Adding Elements: In order to add an element to the map, we can use the put() method. However, the insertion order is not retained in the hashmap. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of Map interface
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Default Initialization of a
        // Map
        Map hm1 = new HashMap();
  
        // Initialization of a Map
        // using Generics
        Map<Integer, String> hm2
            = new HashMap<Integer, String>();
  
        // Inserting the Elements
        hm1.put(1, "Geeks");
        hm1.put(2, "For");
        hm1.put(3, "Geeks");
  
        hm2.put(new Integer(1), "Geeks");
        hm2.put(new Integer(2), "For");
        hm2.put(new Integer(3), "Geeks");
  
        System.out.println(hm1);
        System.out.println(hm2);
    }
}

chevron_right


Output:

{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the map are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of Map interface
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
  
        // Initialization of a Map
        // using Generics
        Map<Integer, String> hm1
            = new HashMap<Integer, String>();
  
        // Inserting the Elements
        hm1.put(new Integer(1), "Geeks");
        hm1.put(new Integer(2), "Geeks");
        hm1.put(new Integer(3), "Geeks");
  
        System.out.println("Initial Map " + hm1);
  
        hm1.put(new Integer(2), "For");
  
        System.out.println("Updated Map " + hm1);
    }
}

chevron_right


Output:

Initial Map {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map {1=Geeks, 2=For, 3=Geeks}

3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of Map interface
  
import java.util.*;
class GFG {
  
    public static void main(String args[])
    {
  
        // Initialization of a Map
        // using Generics
        Map<Integer, String> hm1
            = new HashMap<Integer, String>();
  
        // Inserting the Elements
        hm1.put(new Integer(1), "Geeks");
        hm1.put(new Integer(2), "For");
        hm1.put(new Integer(3), "Geeks");
        hm1.put(new Integer(4), "For");
  
        // Initial Map
        System.out.println(hm1);
  
        hm1.remove(new Integer(4));
  
        // Final Map
        System.out.println(hm1);
    }
}

chevron_right


Output:

{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}

4. Iterating through the Map: There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the working of Map interface
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
  
        // Initialization of a Map
        // using Generics
        Map<Integer, String> hm1
            = new HashMap<Integer, String>();
  
        // Inserting the Elements
        hm1.put(new Integer(1), "Geeks");
        hm1.put(new Integer(2), "For");
        hm1.put(new Integer(3), "Geeks");
  
        for (Map.Entry mapElement : hm1.entrySet()) {
            int key
                = (int)mapElement.getKey();
  
            // Finding the value
            String value
                = (String)mapElement.getValue();
  
            System.out.println(key + " : "
                               + value);
        }
    }
}

chevron_right


Output:



1 : Geeks
2 : For
3 : Geeks

Characteristics of a Map Interface

  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 the specific implementations. For example, TreeMap and LinkedHashMap have predictable order, while HashMap does not.
  3. There are two interfaces for implementing Map in java. They are, 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:

  • A map of error codes and their descriptions.
  • A map of zip codes and cities.
  • A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
  • A map of classes and students. Each class (key) is associated with a list of students (value).

Creating Map Objects

Since Map is an interface, objects cannot be created of the type map. We always need a class which extends this map in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Map. This type-safe map can be defined as:

// Obj is the type of the object to be stored in Map
Map hm = new HashMap ();

Classes which implement the Map interface

1. HashMap: HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. This class uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. Let’s see how to create a map object using this class.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate the Hashmap Class
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        Map<String, Integer> map
            = new HashMap<>();
  
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
  
        for (Map.Entry<String, Integer> e : map.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
    }
}

chevron_right


Output:

vaibhav 20
vishal 10
sachin 30

2. LinkedHashMap: LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. Let’s see how to create a map object using this class.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate the LinkedHashmap Class
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        Map<String, Integer> map
            = new LinkedHashMap<>();
  
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
  
        for (Map.Entry<String, Integer> e : map.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
    }
}

chevron_right


Output:

vishal 10
sachin 30
vaibhav 20

3. TreeMap: The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. Let’s see how to create a map object using this class.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate the Treemap Class
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        Map<String, Integer> map
            = new TreeMap<>();
  
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
  
        for (Map.Entry<String, Integer> e : map.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
    }
}

chevron_right


Output:

sachin 30
vaibhav 20
vishal 10

Methods in Map Interface

Method Description
clear() This method is used to clear and remove all of the elements or mappings from a specified Map collection.
containsKey(Object) This method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
containsValue(Object) This method is used to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is mapped by any of the key in the map.
entrySet() This method is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them.
equals(Object) This method is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
get(Object) This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
hashCode() This method is used to generate a hashCode for the given map containing key and values.
isEmpty() This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true.
keySet() This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
put(Object, Object) This method is used to associate the specified value with the specified key in this map.
putAll(Map) This method is used to copy all of the mappings from the specified map to this map.
remove(Object) This method is used to remove the mapping for a key from this map if it is present in the map.
size() This method is used to return the number of key/value pairs available in the map.
values() This method is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Improved By : Chinmoy Lenka, KaashyapMSK