Map Interface in Java
Last Updated : 08 Aug, 2025
In Java, the Map Interface is part of the [Link] package and
represents a collection of key-value pairs, where:
Keys are unique (no duplicates allowed).
Each key maps to exactly one value.
Values can be duplicates.
Key Features of Map
No Duplicates in Keys: Keys should be unique, but
values can be duplicated.
Null Handling: It allows one null key in implementations
like HashMap and LinkedHashMap, and allows multiple null
values in most implementations.
Thread-Safe Alternatives: Use ConcurrentHashMap for
thread-safe operations. Also, wrap an existing map using
[Link]() for synchronized access.
The Map data structure in Java is implemented by two interfaces:
Map Interface
SortedMap Interface
The three primary classes that implement these interfaces are,
HashMap
TreeMap
LinkedHashMap
Now, let us go through a simple example first to understand the
concept.
Example: Java Program Implementing Map using its implemented
class HashMap
import [Link];
import [Link];
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
[Link]("Geek1", 1);
[Link]("Geek2", 2);
[Link]("Geek3", 3);
[Link]("Map elements: " + m);
Output
Map elements: {Geek3=3, Geek2=2, Geek1=1}
Hierarchy of Map
Creating Map Objects
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
import [Link].*;
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
[Link]("a", new Integer(100));
[Link]("b", new Integer(200));
[Link]("c", new Integer(300));
[Link]("d", new Integer(400));
// Traversing through Map using for-each loop
for ([Link]<String, Integer> me :
[Link]()) {
[Link]([Link]() + ":");
[Link]([Link]());
Output
a:100
b:200
c:300
d:400
Implemented 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.
Operations on Map using HashMap
Now, let’s see how to perform a few frequently used operations on
a Map using the widely used HashMap class.
1. Adding Elements
To 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:
import [Link].*;
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
[Link](1, "Geeks");
[Link](2, "For");
[Link](3, "Geeks");
[Link](new Integer(1), "Geeks");
[Link](new Integer(2), "For");
[Link](new Integer(3), "Geeks");
[Link](hm1);
[Link](hm2);
}
}
Output
{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:
import [Link].*;
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
[Link](new Integer(1), "Geeks");
[Link](new Integer(2), "Geeks");
[Link](new Integer(3), "Geeks");
[Link]("Initial Map: " + hm1);
[Link](new Integer(2), "For");
[Link]("Updated Map: " + hm1);
}
}
Output
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:
import [Link].*;
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
[Link](new Integer(1), "Geeks");
[Link](new Integer(2), "For");
[Link](new Integer(3), "Geeks");
[Link](new Integer(4), "For");
[Link](hm1);
[Link](new Integer(4));
[Link](hm1);
}
}
Output
{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:
import [Link].*;
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
[Link](new Integer(1), "Geeks");
[Link](new Integer(2), "For");
[Link](new Integer(3), "Geeks");
for ([Link] mapElement : [Link]()) {
int key = (int)[Link]();
// Finding the value
String value = (String)[Link]();
[Link](key + " : " + value);
}
}
}
Output
1 : Geeks
2 : For
3 : Geeks
Java program to Count the Occurrence of numbers
using Hashmap
Example:
import [Link].*;
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 < [Link]; i++) {
[Link](a[i]);
}
HashMap<Integer, Integer> hm = new HashMap();
// counting occurrence of numbers
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i), [Link](
al, [Link](i)));
}
[Link](hm);
}
}
Output
{1=2, 2=1, 4=2, 41=1, 13=2, 31=2}
Methods in Java Map Interface
Methods Action Performed
This method is used in Java Map Interface to
clear() 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(Obje
Checks if a value exists in the map.
ct)
Returns a set view of the map’s key-value
entrySet()
pairs.
Methods Action Performed
equals(Object) Compares two maps for equality.
Returns the value for the given key, or null if
get(Object)
not found.
This method is used in Map Interface to
hashCode() generate a hashCode for the given map
containing keys and values.
This method is used to check if a map is
isEmpty() 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.
This method is used in Java Map Interface to
put(Object, Object) associate the specified value with the specified
key in this map.
This method is used in Map Interface in Java to
putAll(Map) copy all of the mappings from the specified
map to this map.
This method is used in Map Interface to
remove(Object) remove the mapping for a key from this map if
it is present in the map.
This method is used to return the number of
size()
key/value pairs available in the map.
values() Returns a collection view of the map’s values.
Methods Action Performed
getOrDefault(Objec Returns the value to which the specified key is
t key, V mapped, or defaultValue if this map contains
defaultValue) no mapping for the key.
merge(K key, V
value, BiFunction<?
If the specified key is not already associated
super V,? super V,?
with a value or is associated with null,
extends V>
associate it with the given non-null value.
remappingFunction
)
putIfAbsent(K key, Adds a mapping only if the key is not already
V value) mapped.
Java Comparator Interface
In Java, the Comparator interface is a part of [Link] package and it defines
the order of the objects of user-defined classes.
Methods of Comparator Interface
The Comparator interface defines two methods: compare() and equals().
The compare() method, shown here, compares two elements for order −
The compare() Method
int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the
objects are equal. It returns a positive value if obj1 is greater than obj2.
Otherwise, a negative value is returned.
By overriding compare(), you can alter the way that objects are ordered. For
example, to sort in a reverse order, you can create a comparator that reverses
the outcome of a comparison.
The equals() Method
The equals() method, shown here, tests whether an object equals the invoking
comparator −
boolean equals(Object obj)
obj is the object to be tested for equality. The method returns true if obj and
the invoking object are both Comparator objects and use the same ordering.
Otherwise, it returns false.
Overriding equals() is unnecessary, and most simple comparators will not do
so.
Comparator Interface to Sort a Custom Object
In this example, we're using Comparator interface to sort a custom object Dog
based on comparison criterias.
Example
import [Link];
import [Link];
import [Link];
import [Link];
class Dog implements Comparator<Dog>, Comparable<Dog> {
private String name;
private int age;
Dog() {
}
Dog(String n, int a) {
name = n;
age = a;
public String getDogName() {
return name;
public int getDogAge() {
return age;
// Overriding the compareTo method
public int compareTo(Dog d) {
return ([Link]).compareTo([Link]);
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1) {
return [Link] - [Link];
@Override
public String toString() {
return [Link] + "," + [Link];
public class ComparatorDemo {
public static void main(String args[]) {
// Takes a list o Dog objects
List<Dog> list = new ArrayList<>();
[Link](new Dog("Shaggy", 3));
[Link](new Dog("Lacy", 2));
[Link](new Dog("Roger", 10));
[Link](new Dog("Tommy", 4));
[Link](new Dog("Tammy", 1));
[Link](list); // Sorts the array list
[Link]("Sorted by name:");
// printing the sorted list of names
[Link](list);
// Sorts the array list using comparator
[Link](list, new Dog());
[Link](" ");
[Link]("Sorted by age:");
// printing the sorted list of ages
[Link](list);
Output
Sorted by name:
[Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4]
Sorted by age:
[Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10]
Comparator Interface to Reverse Sort
In this example, we're using Comparator interface to reverse sort the Dog
objects.
Example 2
import [Link];
import [Link];
import [Link];
import [Link];
class Dog implements Comparator<Dog>, Comparable<Dog> {
private String name;
private int age;
Dog() {
Dog(String n, int a) {
name = n;
age = a;
public String getDogName() {
return name;
public int getDogAge() {
return age;
// Overriding the compareTo method
public int compareTo(Dog d) {
return ([Link]).compareTo([Link]);
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1) {
return [Link] - [Link];
@Override
public String toString() {
return [Link] + "," + [Link];
public class ComparatorDemo {
public static void main(String args[]) {
// Takes a list o Dog objects
List<Dog> list = new ArrayList<>();
[Link](new Dog("Shaggy", 3));
[Link](new Dog("Lacy", 2));
[Link](new Dog("Roger", 10));
[Link](new Dog("Tommy", 4));
[Link](new Dog("Tammy", 1));
[Link](list, [Link]()); // Sorts the array list
[Link]("Sorted by name in reverse order:");
// printing the sorted list of names
[Link](list);
}
}
Output
Sorted by name in reverse order:
[Tommy,4, Tammy,1, Shaggy,3, Roger,10, Lacy,2]
Java Comparable Interface
Comparable interface is a very important interface which can be used
by Java Collections to compare custom objects and sort them. Using
comparable interface, we can sort our custom objects in the same way
how wrapper classes, string objects get sorted using Collections sorting
methods.
Using comparable, we can make the elements as sortable.
Comparable Interface Methods
The Comparable interface defines a methods: compareTo(). The compareTo()
method, shown here, compares the passed object for order −
The compare() Method
int compareTo(Object obj)
obj is the object to be compared. This method returns zero if the objects are
equal. It returns a positive value if current object is greater than obj.
Otherwise, a negative value is returned.
By overriding compareTo(), you can alter the way that objects are ordered. For
example, to sort in a reverse order, you can implement a comparison method
that reverses the outcome of a comparison.
The equals() Method
The equals() method, shown here, tests whether an object equals the invoking
comparator −
boolean equals(Object obj)
obj is the object to be tested for equality. The method returns true if obj and
the invoking object are both Comparator objects and use the same ordering.
Otherwise, it returns false.
Overriding equals() is unnecessary, and most simple comparators will not do
so.
Comparable Interface to Sort Custom Object
In this example, we're using Comparable interface to sort a custom object Dog
based on comparison criterias.
Example
import [Link];
import [Link];
import [Link];
class Dog implements Comparable<Dog> {
private String name;
private int age;
Dog() {
Dog(String n, int a) {
name = n;
age = a;
public String getDogName() {
return name;
public int getDogAge() {
return age;
// Overriding the compareTo method
public int compareTo(Dog d) {
// compare the name using alphabetical order
return ([Link]).compareTo([Link]);
@Override
public String toString() {
return [Link] + "," + [Link];
public class ComparableDemo {
public static void main(String args[]) {
// Takes a list o Dog objects
List<Dog> list = new ArrayList<>();
[Link](new Dog("Shaggy", 3));
[Link](new Dog("Lacy", 2));
[Link](new Dog("Roger", 10));
[Link](new Dog("Tommy", 4));
[Link](new Dog("Tammy", 1));
[Link](list); // Sorts the array list
[Link]("Sorted by name:");
// printing the sorted list of names
[Link](list);
Output
This will produce the following result −
Sorted by name:
[Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4]
Comparator vs Comparable
Comparator Comparable
Sorting logic is defined Sorting logic is defined within the
externally. class (Internally)
Does not support multiple sorting
Supports multiple sorting orders.
orders.
Uses the compare() method Uses the compareTo() method.
It is also a functional interface
It is a functional interface.
(since Java 8)
More flexible and reusable Simple and tightly coupled