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.
The following image shows the hierarchy of the Map interface and its implementations:

The following points explain why the Map interface is useful:
The following points describe the key features of the Map interface:
The following table describes the commonly used classes that implement the Map interface:
| Class | Description |
|---|---|
| HashMap | HashMap is the implementation of Map, but it doesn't maintain any order. |
| LinkedHashMap | LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order. |
| TreeMap | TreeMap is the implementation of Map and SortedMap. It maintains ascending order. |
| HashTable | Java 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. |
The following table shows the commonly used methods of the Map interface:
| Method | Description |
|---|---|
| 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. |
| Collection | It returns a collection view of the values contained in the map. |
| int size() | This method returns the number of entries in the map. |
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);
}
}
Output:
{99=Jack, 100=Andrew, 101=Tom}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);
}
}
Output:
{99=Emma, 100=David, 101=Robert}
After updation:
{99=Emma, 100=David, 101=Robert, 102=Noah}
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);
}
}
Output:
{99=Mary, 100=Oliver, 101=Theodore}
After removing key 100 and its mapping:
{99=Mary, 101=Theodore}
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());
}
}
}
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
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
}
}
Output:
100=Smith 101=Williams 102=Johnson
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
}
}
Output:
102=Liam 101=Williams 100=Garcia
We request you to subscribe our newsletter for upcoming updates.