Java Map Interface

Last Updated : 23 Sept 2026

Java Map interface holds a set of key-value pairs where each key is unique and points to one value only. It belongs to java.util package. A Map is useful if one has to search, update, or delete elements on the basis of a key.

In this chapter, you will learn about the Java Map interface, its features, and examples.

Hierarchy of Map Interface

The following image shows the hierarchy of the Map interface and its implementations:

Java Map Hierarchy

Why to Use Map Interface?

The following points explain why the Map interface is useful:

  • Efficient Data Retrieval: Map allows fast searching of values using keys. It is very useful when you need to quickly access data from a large dataset.
  • No Duplicate Keys: Each key in a Map is unique and maps to only one value. This helps maintain data consistency and avoids duplicate entries.
  • Flexible Data Types: We can store different types of objects as keys and values in a Map. This makes it flexible for representing different types of relationships.
  • Associative Structure: Map works like a dictionary where each key is linked to a value. It helps in organizing data in a meaningful and structured way.
  • Caching and Memoization: Map can store results of operations so they can be reused later. It improves performance by avoiding repeated calculations.

Features of Map Interface

The following points describe the key features of the Map interface:

  • Key-Value Pair Structure: Map stores data in the form of key and value pairs. Each key is used to access its corresponding value.
  • No Duplicate Keys: A Map does not allow duplicate keys, but it can have duplicate values. If you add a duplicate key, the old value is replaced with the new value.
  • Allows Null Values: Some Map implementations allow null keys and values. For example, HashMap allows one null key and multiple null values.
  • Not a Subtype of Collection: Map is not a part of the Collection interface. It is a separate interface in the Java Collections Framework.
  • Traversal Using Set: A Map cannot be traversed directly. To iterate over it, you need to use keySet(), values(), or entrySet() methods.
  • Different Implementations: Map has different implementations like HashMap, LinkedHashMap, and TreeMap. Each implementation works differently based on ordering and performance.

Classes of Map Interface

The following table describes the commonly used classes that implement the Map interface:

ClassDescription
HashMapHashMap is the implementation of Map, but it doesn't maintain any order.
LinkedHashMapLinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
TreeMapTreeMap is the implementation of Map and SortedMap. It maintains ascending order.
HashTableJava Hashtable is a class that implements the Map interface and is used to store key-value pairs with unique keys. It uses a hash table data structure internally, where a hash function determines the index of elements stored in buckets.

Methods of the Map Interface

The following table shows the commonly used methods of the Map interface:

MethodDescription
V put(Object key, Object value)It is used to insert an entry in the map.
void putAll(Map map)It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)It removes the specified values with the associated specified keys from the map.
Set keySet()It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet()It returns the Set view containing all the keys and values.
void clear()It is used to reset the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key)This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode()It returns the hash code value for the Map
boolean isEmpty()This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collectionvalues()It returns a collection view of the values contained in the map.
int size()This method returns the number of entries in the map.

Map Operations

Example: Adding Elements

In this example, we have used a HashMap. The put() method for adding elements to the map. Note that in a HashMap, insertion order is not preserved.

Java

import java.util.*;  
public class Main {  
   public static void main(String args[]) {  
      // Creating a HashMap instance  
      // Here, the key is of type Integer, and the value is of type String
      Map<Integer, String> map = new HashMap<Integer, String>();     
      // Adding key-value pairs to the map  
      map.put(100, "Andrew");  
      map.put(101, "Tom");  
      map.put(99, "Jack");   
      // displaying the map 
      System.out.println(map);   
      
   }  
}  
Compile and Run

Output:

{99=Jack, 100=Andrew, 101=Tom}

Example: Updating Elements

The Map.put() method can also be used for updating values of a map. For a specified key, the put() method can update its value.

Java

import java.util.*;  
public class Main {  
   public static void main(String args[]) {  
      // Creating a HashMap instance  
      // Here, the key is of type Integer, and the value is of type String
      Map<Integer, String> map = new HashMap<Integer, String>();     
      // Adding key-value pairs to the map  
      map.put(100, "David");  
      map.put(101, "Robert");  
      map.put(99, "Emma");   
      // displaying the map 
      System.out.println(map);
      map.put(102, "Noah"); // value of key 100 is updated
      System.out.println("After updation: ");
      System.out.println(map);
   }  
}  
Compile and Run

Output:

{99=Emma, 100=David, 101=Robert}
After updation: 
{99=Emma, 100=David, 101=Robert, 102=Noah}

Example: Removing Elements

The Map.remove() method can be used for removing elements from a map. For a specified key (if the key is present in the map), the Map.remove() method removes its mapping from the map.

Java

import java.util.*;  
public class Main {  
   public static void main(String args[]) {  
      // Creating a HashMap instance  
      // Here, the key is of type Integer, and the value is of type String
      Map<Integer, String> map = new HashMap<Integer, String>();     
      // Adding key-value pairs to the map  
      map.put(100, "Oliver");  
      map.put(101, "Theodore");  
      map.put(99, "Mary");   
      // displaying the map 
      System.out.println(map);
      map.remove(100); // key 100 is removed
      System.out.println("After removing key 100 and its mapping: ");
      System.out.println(map);
   }  
}  
Compile and Run

Output:

{99=Mary, 100=Oliver, 101=Theodore}
After removing key 100 and its mapping: 
{99=Mary, 101=Theodore}

Example: Iterating Over Elements

There are various ways to iterate through a map. In this example, we have used an iterator and a for-each loop.

Java

import java.util.*;
public class Main {
    public static void main(String args[]) {
        // Creating an instance of HashMap
        // Here, Integer is the key, and String is the value
        Map<Integer, String> hm = new HashMap<Integer, String>();
        System.out.println("Traversing using for-each loop");
        // Inserting the Elements
        hm.put(1, "T");
        hm.put(2, "Point");
        hm.put(3, "Tech");
        hm.put(0, "Java");
        // for each loop
        for (Map.Entry mapEle : hm.entrySet()) {
            int key = (int)mapEle.getKey();
            // Finding the value
            String val = (String)mapEle.getValue();
            System.out.println(key + ": " + val);
        }
        System.out.println();
        System.out.println("Traversing using an iterator");
        // Traversing Map using iterator
        // Converting to Set so that we can traverse  
        Set set = hm.entrySet(); 
        Iterator itr = set.iterator();  
        while(itr.hasNext()) {  
            // Converting to Map.Entry so that we can get key and value separately  
            Map.Entry en = (Map.Entry)itr.next();  
            System.out.println(en.getKey() + ": " + en.getValue());  
        }
    }
}
Compile and Run

Output:

Traversing using for-each loop
0: Java
1: T
2: Point
3: Tech

Traversing using an iterator
0: Java
1: T
2: Point
3: Tech

Example: Sorting Map by Key (Ascending Order)

In this example, we are sorting the Map entries by key in ascending order.

Java

import java.util.*;  
public class Main {  
    public static void main(String args[]) {  
        // Creating a HashMap instance to store key-value pairs  
        Map<Integer, String> map = new HashMap<Integer, String>();  
        // Adding key-value pairs to the map  
        map.put(100, "Smith");  
        map.put(101, "Williams");  
        map.put(102, "Johnson");  
        // Returns a Set view of the mappings contained in this map  
        map.entrySet() // Returns a Set view of the mappings contained in this map  
            .stream() // Returns a sequential Stream with this collection as its source  
            .sorted(Map.Entry.comparingByKey()) // Sorted according to the provided Comparator  
            .forEach(System.out::println); // Performs an action for each element of this stream  
    }  
}  
Compile and Run

Output:

100=Smith
101=Williams
102=Johnson

Example: Sorting Map by Key (Descending Order)

In this example, we are sorting the Map entries by key in descending order.

Java

import java.util.*;  
public class Main {  
    public static void main(String args[]) {  
        // Creating a HashMap instance to store key-value pairs  
        Map<Integer, String> map = new HashMap<Integer, String>();  
        // Adding key-value pairs to the map  
        map.put(100, "Garcia");  
        map.put(101, "Williams");  
        map.put(102, "Liam");  
        // Returns a Set view of the mappings contained in this map  
        map.entrySet() // Returns a Set view of the mappings contained in this map  
            .stream() // Returns a sequential Stream with this collection as its source  
            .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) // Sorted according to the provided Comparator  
            .forEach(System.out::println); // Performs an action for each element of this stream  
    }  
}  
Compile and Run

Output:

102=Liam
101=Williams
100=Garcia