The ‘Map’ interface represents a collection of key-value pairs. Each key in the map is associated with exactly one value, creating a relationship between the two. Keys in a map are unique, meaning no two entries can have the same key. Unlike other collection types, like lists and sets, which handle individual elements. A map organises data as pairs, where each unique key is associated with a specific value. This article explores the ‘Map’ interface, its features, and its common implementation.
Introduction to the Map Interface
The Java ‘Map’ interface is part of the Java Collection framework. It provides a way to store key-value pairs. Unlike lists or sets, which only store values, a’ Map’ associates each key with a specific value. This makes it easier to look up data based on a key.
The ‘Map’ interface stores data in key-value pairs. Each key maps to a specific value.
In the Map interface, Keys are unique. If you attempt to insert a new value with an existing key, the old value associated with that key is replaced.
Map interfaces, such as HashMap, allow one null key and multiple null values. Other implementations, like TreeMap, do not allow null keys but can have null values.
We can iterate over the keys, values or entries(key-value pairs) using the keySet(), values(), and entrySet() methods, respectively.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Features of Map Interface
The ‘Map’ interface in Java is a versatile tool for handling collections of data where each element is stored as a key-value pair. Here are some of the key features:
Key-Value Storage: Each element in a “Map” consists of a key and a value. The key is unique, and it maps to exactly one value.
Unique Keys: Each key must be unique in the map interface.
Efficient Operations: Quick retrieval, insertion, and deletion of elements.
Null Handling: Allows null keys and /or values depending on the implementation.
Thread Safety: Implementations like ‘HashMap’ and’ LinkedHashMap’ are not thread-safe; use ‘ConcurrentHashMap’ for thread-safe operations.
Hierarchy of the Map Interface in Java
The ‘Map’ interface in Java is part of the Java Collection Framework and represents a collection of key-value pairs. It provides a blueprint for how key-value pairs are managed, and several classes implement this interface to provide different types of map behaviours. Here’s an overview of the hierarchy of the ‘Map’ interface in the Java language.
Below is a diagram showing the standard map interface hierarchy:
Class that implements Map
Class
Description
HashMap
HashMap implements the Map interface and does not maintain any specific order.
LinkedHashMap
The implementation of Map is LinkedHashMap. It inherits the class HashMap. The insertion order is maintained.
TreeMap
The map and the sorted map interfaces are implemented. In TreeMap, the order is always maintained in ascending order.
Interfaces the extended Map
Interface
Description
Map
The Map is not allowed in a map. It allows duplicate values.
SortedMap
In the sorted map, Elements can be traversed in the sorted order of their keys.
Creating Map Objects
Creating a map object in Java is very straightforward. However, we cannot create an object of the type map. We always need a class that extends this map to create an object. After they introduced Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Map.
Syntax
Map mp = new HashMap() ;
Characteristics of a Map Interface
The ‘Map’ interface in Java represents a collection that maps keys to values. A map cannot contain duplicate duplicate keys, and each key can map to at most one value. Here are some key characteristics of the ‘Map’ interface.
Key-Value Pairs: A ‘Map’ stores elements in key-value pairs. Each key is unique, and each key maps to one value.
No Duplicate Keys: The value can be duplicated, but the key must be unique.
No Duplicate Keys: Maps do not allow duplicate keys. If a duplicate key is inserted, the new value associated with that key will overwrite the existing value.
Null Keys and Values: They allow one ‘null’ key and multiple ‘null’ values in some implementations (eg “HashMap”).
Thread Safety: Not thread-safe by default. Use ConcurrentHashMap or external synchronisation for concurrent access.
When to Use the Map interface in Java?
The ‘Map’ interface is useful when you need to store and retrieve data based on a unique key. Here are some common situations where you might choose to use a ‘map’.
Associating Unique Keys with Values: Use the ‘Map’ when you need to associate unique keys with specific values. For example, store a dictionary where each word(key) maps to its definition(value).
Fast Lookups: When your application requires fast retrieval of values based on a key, a “Map” is an ideal choice. For instance, when you implement a cache where you quickly need to find a value using a unique identifier.
Mapping Relationships: If you are modelling relationships between objects, such as a student (key) and their grades (value). A “Map” provides a clear and efficient way to manage these relationships.
Dynamic Key-Value Pair Management: Map offers flexibility where we need to add, remove or update a Map.
Methods of Map Interface
Method
Action Performed
put(key,value)
In this method, the Given value and key are associated together using this method.
containsKey(key)
This method matches the key that exists in the map. This method returns true otherwise false.
containsValue(Value)
This method matches the value that exists in the map. If the matches are found then returns true otherwise. IT returns false.
isEmpty()
The map has no keys. This method returns true otherwise returns false.
clear()
This method is used to clear all the elements in a map
remove(key)
This method removes an entry for the given key
remove(key,value)
The given values and their corresponding specified keys are removed from the map.
entrySet()
It returns the set view, which includes each key and value.
values()
This method contains the map and is returned as a collection view.
putAll(Map)
This method is used to put the specified map into the map
Operations Using Map Interface and HashMap Class
In this section, we explore some commonly performed operations on a Map interface. We will use the HashMap class, which implements the ‘Map’ interface using a hash table. It allows null values and the null key, which makes it unique among other ‘Map’ implementations like’ Hashtable’. Here are some operations that we will perform:
Adding Elements
Changing Element
Removing Element
Iterating through the Map
Adding Elements
In Java, the put() method is used to add a new element to the map. However, the hashmap does not keep track of the insertion order. Internally, a unique has been generated for each element, and the elements are indexed based on this hash to increase efficiency. The time complexity for adding the element is O(1).
The following program demonstrates the adding elements in Java.
Program
import java.util.*;
class Main {
public static void main(String args[]){
// Standard Initialization of a Map
Map<Integer, String> map1 = new HashMap<>();
// Initialization of a Map using Generics
Map<Integer, String> map2 = new HashMap<Integer, String>();
// Inserting the Elements
map1.put(1, "Java");
map1.put(2, "C++");
map1.put(3, "Python ");
map2.put(new Integer(1), "Java");
map2.put(new Integer(2), "C++");
map2.put(new Integer(3), "Python");
// Print the map using sout
System.out.println(map1);
System.out.println(map2);
}
}
We also update an element after adding HashMap by using the put() method. The values of the keys Since the elements in the map are indexed using the keys. We can change the value of the key by simply inserting the new value. The time complexity for changing the element in O(1).
The following program demonstrates the program:
Program
// Java program to understand the working of the Map interface
import java.util.*;
class Main {
public static void main(String args[])
{
Map<Integer, String> map
= new HashMap<Integer, String>();
// Inserting the Elements
map.put(new Integer(1), "Learn");
map.put(new Integer(2), "in");
map.put(new Integer(3), "Hero Vired");
System.out.println("Original Map " + map);
map.put(new Integer(2), "with");
System.out.println("Updated Map " + map);
}
}
The remove() method can be used from the Map. If there is a mapping for a key in the map. We can remove the element from the map interface, which accepts the key value for removing the element from the Map. The time complexity for removing the element is O(1).
The following program demonstrates the removing element:
Program
import java.util.*;
class Main {
public static void main(String args[]){
// Initialization of a Map using Generics
Map<Integer, String> ob = new HashMap<Integer, String>();
// Inserting the Elements
ob.put(new Integer(1), "Kumar");
ob.put(new Integer(2), "Vishal");
ob.put(new Integer(3), "Karan");
ob.put(new Integer(4), "Voldemort");
// Initial Map
System.out.println("Original Map " + ob);
ob.remove(new Integer(4));
// Final Map
System.out.println("Updated Map " +ob);
}
}
We can also iterate the map in a for-each loop. The getValue() method determines the key’s value and iterates through all the elements. The time complexity becomes O(n).
The following program demonstrates the Iterating Map:
Program
import java.util.*;
class Main {
public static void main(String args[]){
// Initialization of a Map using Generics
Map<Integer, String> ob = new HashMap<Integer, String>();
// Inserting the Elements
ob.put(new Integer(1), "Neeraj");
ob.put(new Integer(2), "Voldemort");
ob.put(new Integer(3), "Katherine Langford");
for (Map.Entry mapElement : ob.entrySet()) {
int key = (int)mapElement.getKey();
String value = (String)mapElement.getValue();
System.out.println(key + " : " + value);
}
}
}
Output
1: Neeraj
2: Voldemort
3 : Katherine Langford
Implementing Map Interface in Java
Implementing Map in Java Using the HashMap Class
The HashMap classes provide the basic implementation of the map. We can use a hashing method to access the values from the keys. It stores the elements as a key:value pair.
The following program demonstrates the HashMap class:
Progarm
import java.util.*;
// Main class
public class Main {
// Main driver method
public static void main(String[] args){
// Creating an empty HashMap
Map<String, Integer> cg = new HashMap<>();
// Inserting entries in the Map
// using put() method
cg.put("Voldemort", 10);
cg.put("Katrina Kaif", 30);
cg.put("Robots", 20);
// Iterating over Map
for (Map.Entry<String, Integer> i : cg.entrySet())
// Printing key-value pairs
System.out.println(i.getKey() + " "+i.getValue());
}
}
Output
Katrina Kaif 30
Robots 20
Voldemort 10
Implementing Map in Java Using the LinkedHashMap Class
The LinkedHashMap class in Java is a part of the ‘java.util’ package and extends the ‘HashMap’ class. It maintains a doubly-linked list that defines the iteration ordering, which is typically the order in which elements are inserted into the map. The following program demonstrates the LinkedHashMap
Program
import java.util.*;
// Main class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashMap
Map<String, Integer> cg = new LinkedHashMap<>();
// Inserting entries in the Map
// using put() method
cg.put("Computer", 10);
cg.put("Water Boll", 30);
cg.put("Sanjay Leela ", 20);
// Iterating over Map
for (Map.Entry<String, Integer> i : cg.entrySet())
// Printing key-value pairs
System.out.println(i.getKey() + " "+ i.getValue());
}
}
Output
Computer 10
Water Boll 30
Sanjay Leela 20
Implementing Map Interface in Java Using the TreeMap Class
We can also implement the TreeMap in the Map Interface. It provides a fast way to sort the map and differs from HashMap and LinkedHashMap. The ‘TreeMap’ class is part of Java’s Collection Framework and implements the ‘Map’ interface. The following program demonstrates the TreeMap class in Java:
Program
import java.util.*;
public class Main {
public static void main(String[] args){
Map<String, Integer> map = new TreeMap<>();
cg.put("Doaremon", 10);
cg.put("Voldemort", 30);
cg.put("Cartoon", 20);
for (Map.Entry<String, Integer> i : cg.entrySet())
System.out.println(i.getKey() + " "+i.getValue());
}
}
Output
Computer 10
Water Boll 30
Sanjay Leela 20
Conclusion
The Map interface in Java helps you store data as pairs of keys and values. It makes it easy to find, add or remove items based on their keys. Different types of Maps, like ‘HashMap’, ‘TreeMap’ and ‘LinkedHashMap’. This offers different benefits, such as faster lookups or keeping items in order when they are added.
FAQs
What is the ‘Map’ interface in Java?
The ‘Map’ interface in Java is part of the Java Collection framework. It represents a collection of key-value pairs, where each key is mapped to a specific value. It does not allow duplicate keys, but duplicate values are permitted.
What is the purpose of the ‘put’ method in a ‘Map’?
The ‘put’ method inserts a key-value pair into the map. If the key already exists, it updates the value associated with it.
How does the ‘containsKey’ method work?
The containsKey method checks whether a specific key is present in the map. It returns ‘true’ if the key exists and ‘false’ otherwise.
How do you clear all entries from a ‘Map’?
The' clear' method can remove all items from a map, removing all key-value pairs from the map interface.
What is the ‘default’ method in the ‘Map’ interface?
The ‘Map’ interface provides default methods such as ‘forEach’, ‘replaceAll’, and ‘computeIfAbsent’ that allow you to perform common operations in a functional programming style.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.