Last Updated : 08 Aug, 2025
In Java, the Map Interface is part of the java.util package and represents a collection of key-value pairs, where:
The Map data structure in Java is implemented by two interfaces:
The three primary classes that implement these interfaces are,
Now, let us go through a simple example first to understand the concept.
Example: Java Program Implementing Map using its implemented class HashMap
Java
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args) {
// Create a Map using HashMap
Map<String, Integer> m = new HashMap<>();
// Adding key-value pairs to the map
m.put("Geek1", 1);
m.put("Geek2", 2);
m.put("Geek3", 3);
System.out.println("Map elements: " + m);
}
}
Map elements: {Geek3=3, Geek2=2, Geek1=1}
We must know that why and when to use Maps.
Since Map is an interface, objects cannot be created of the type map. We always need a class that implements this map interface 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<String, Integer> hm = new HashMap<>(); // Type-safe map storing String keys and Integer values
Example: Java Program to Demonstrate working of Map interface
Java
import java.util.*;
class Geeks {
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()) {
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
a:100 b:200 c:300 d:400Implemented Classes of Map Interafe
1. HashMap: HashMap is introduced in Java 1.2, is a basic implementation of the Map interface that stores data in key-value pairs. It uses hashing to convert large strings into shorter ones for efficient indexing and faster searches.s.
2. LinkedHashMap: LinkedHashMap is like HashMap but maintains the insertion order of elements. It supports fast insertion, search, and deletion while keeping track of the order in which keys were added.
3. TreeMap: TreeMap implements Map and NavigableMap, storing key-value pairs in sorted order, either by natural key ordering or a custom Comparator. The ordering must be consistent with equals() if no custom comparator is used.
Now, let’s see how to perform a few frequently used operations on a Map using the widely used HashMap class.
1. Adding ElementsTo add an element to the map, we can use the put() method. 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
import java.util.*;
class Geeks {
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}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. 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 want to change.
Example:
Java
import java.util.*;
class Geeks {
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}3. Removing Elements
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
import java.util.*;
class Geeks {
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");
System.out.println(hm1);
hm1.remove(new Integer(4));
System.out.println(hm1);
}
}
{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.
Example:
Java
import java.util.*;
class Geeks {
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 : GeeksJava program to Count the Occurrence of numbers using Hashmap
Example:
Java
import java.util.*;
class Geeks {
public static void main(String[] args)
{
int a[] = { 1, 13, 4, 1, 41, 31, 31, 4, 13, 2 };
// put all elements in arraylist
ArrayList<Integer> al = new ArrayList();
for (int i = 0; i < a.length; i++) {
al.add(a[i]);
}
HashMap<Integer, Integer> hm = new HashMap();
// counting occurrence of numbers
for (int i = 0; i < al.size(); i++) {
hm.putIfAbsent(al.get(i), Collections.frequency(
al, al.get(i)));
}
System.out.println(hm);
}
}
{1=2, 2=1, 4=2, 41=1, 13=2, 31=2}Methods in Java Map Interface Methods Action Performed clear() This method is used in Java Map Interface to clear and remove all of the elements or mappings from a specified Map collection. containsKey(Object) Checks if a key exists in the map. containsValue(Object) Checks if a value exists in the map. entrySet() Returns a set view of the map’s key-value pairs. equals(Object) Compares two maps for equality. get(Object) Returns the value for the given key, or null if not found. hashCode() This method is used in Map Interface to generate a hashCode for the given map containing keys 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() Returns a set view of the keys in the map. put(Object, Object) This method is used in Java Map Interface to associate the specified value with the specified key in this map. putAll(Map) This method is used in Map Interface in Java to copy all of the mappings from the specified map to this map. remove(Object) This method is used in Map Interface 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() Returns a collection view of the map’s values. getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. 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, associate it with the given non-null value. putIfAbsent(K key, V value) Adds a mapping only if the key is not already mapped.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4