Map Interface in Java - GeeksforGeeks

11 May, 2022
The map interface is 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.
Geeks, the brainstormer should have been 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 common scenarios are as follows: 
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).
Since Map is an interface, objects cannot be created of the type map. We always need a class that 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. 
Syntax: Defining Type-safe Map
Map hm = new HashMap(); 
// Obj is the type of the object to be stored in Map
A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null values like the HashMap and LinkedHashMap, but some do not like the TreeMap.The order of a map depends on the specific implementations. For example, TreeMap and LinkedHashMap have predictable orders, while HashMap does not.There are two interfaces for implementing Map in java. They are Map and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null values like the HashMap and LinkedHashMap, but some do not like the TreeMap.
The order of a map depends on the specific implementations. For example, TreeMap and LinkedHashMap have predictable orders, while HashMap does not.
There are two interfaces for implementing Map in java. They are Map and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
 Example:
Java
// Java Program to Demonstrate// Working of Map interface  // Importing required classesimport java.util.*;  // Main classclass GFG {      // Main driver method    public static void main(String args[])    {        // Creating an empty HashMap        Map<String, Integer> hm            = new HashMap<String, Integer>();          // Inserting pairs in above Map        // using put() method        hm.put("a", new Integer(100));        hm.put("b", new Integer(200));        hm.put("c", new Integer(300));        hm.put("d", new Integer(400));          // Traversing through Map using for-each loop        for (Map.Entry<String, Integer> me :             hm.entrySet()) {              // Printing keys            System.out.print(me.getKey() + ":");            System.out.println(me.getValue());        }    }}
a:100
b:200
c:300
d:400
 
Classes that implement the Map interface are depicted in the below media and described later as follows:
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 a 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.
Example 
Java
// Java Program to illustrate the Hashmap Class  // Importing required classesimport java.util.*;  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)    {          // Creating an empty HashMap        Map<String, Integer> map = new HashMap<>();          // Inserting entries in the Map        // using put() method        map.put("vishal", 10);        map.put("sachin", 30);        map.put("vaibhav", 20);          // Iterating over Map        for (Map.Entry<String, Integer> e : map.entrySet())              // Printing key-value pairs            System.out.println(e.getKey() + " "                               + e.getValue());    }}
vaibhav 20
vishal 10
sachin 30
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.
Example  
Java
// Java Program to Illustrate the LinkedHashmap Class  // Importing required classesimport java.util.*;  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)    {          // Creating an empty LinkedHashMap        Map<String, Integer> map = new LinkedHashMap<>();          // Inserting pair entries in above Map        // using put() method        map.put("vishal", 10);        map.put("sachin", 30);        map.put("vaibhav", 20);          // Iterating over Map        for (Map.Entry<String, Integer> e : map.entrySet())              // Printing key-value pairs            System.out.println(e.getKey() + " "                               + e.getValue());    }}
vishal 10
sachin 30
vaibhav 20
 
The TreeMap in Java is used to implement the 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.
Example  
Java
// Java Program to Illustrate TreeMap Class  // Importing required classesimport java.util.*;  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)    {          // Creating an empty TreeMap        Map<String, Integer> map = new TreeMap<>();          // Inserting custom elements in the Map        // using put() method        map.put("vishal", 10);        map.put("sachin", 30);        map.put("vaibhav", 20);          // Iterating over Map using for each loop        for (Map.Entry<String, Integer> e : map.entrySet())              // Printing key-value pairs            System.out.println(e.getKey() + " "                               + e.getValue());    }}
sachin 30
vaibhav 20
vishal 10
 
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. 
Operation 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.
Example 
Java
// 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<Integer, String> 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);    }}
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
 
Operation 2: Changing Element
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. 
Example 
Java
// 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);    }}
Initial Map {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map {1=Geeks, 2=For, 3=Geeks}
 
Operation 3: Removing Elements
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.
Example  
Java
// 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);    }}
{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}
 
Operation 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.
Example  
Java
// 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);        }    }}
1 : Geeks
2 : For
3 : Geeks
 
Chinmoy Lenka
KaashyapMSK
dhananjay gore
nishkarshgandhi
surinderdawra388
Java - util package
Java-Collections
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Reverse a string in Java
Arrays.sort() in Java with examples
Stream In Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Initializing a List in Java
Generics in Java
Different ways of Reading a text file in Java