Java Map

Introduction

The Java Map interface is one of the most important components of the Java Collections Framework. Unlike the List, Set, and Queue interfaces, which store individual elements, a Map stores data as key-value pairs. Each key is unique and maps to exactly one value, making the Map interface ideal for fast data retrieval.

The Map interface belongs to the java.util package and is widely used in Java applications for storing configuration settings, user information, product details, employee records, caching data, and database-like structures.

Java provides several implementations of the Map interface, including HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap, and EnumMap, each with different characteristics regarding ordering, performance, synchronization, and null handling.

What is Java Map?

A Map is a data structure that stores information in the form of key-value pairs.

  • Each key is unique.
  • Multiple keys can have the same value.
  • If the same key is inserted again, the old value is replaced with the new one.

Example:

Key Value
101 Rahul
102 Amit
103 Neha

In this example:

  • Keys: 101, 102, 103
  • Values: Rahul, Amit, Neha

A Map allows you to quickly retrieve a value using its corresponding key.

Java Map Hierarchy


Map
 │
 ├── HashMap
 ├── LinkedHashMap
 ├── TreeMap
 ├── Hashtable
 ├── ConcurrentHashMap
 └── EnumMap

Popular Implementations

  • HashMap – Fastest and most commonly used.
  • LinkedHashMap – Maintains insertion order.
  • TreeMap – Stores keys in sorted order.
  • Hashtable – Thread-safe legacy implementation.
  • ConcurrentHashMap – Thread-safe and optimized for concurrent applications.
  • EnumMap – Specialized implementation for enum keys.

Features of Java Map

Some important features include:

  • Stores data as key-value pairs
  • Keys must be unique
  • Values can be duplicated
  • Fast retrieval using keys
  • Dynamic size
  • Supports Generics
  • Multiple implementations available
  • Different implementations provide different ordering behavior

Syntax

Import Statement


import java.util.Map;
import java.util.HashMap;

or


import java.util.*;

Creating a Map

Using HashMap:


Map<Integer, String> students = new HashMap<>();

Using LinkedHashMap:


Map<Integer, String> students = new LinkedHashMap<>();

Using TreeMap:


Map<Integer, String> students = new TreeMap<>();

Common Methods of Map

Method Description
get() Returns the value associated with a key
remove() Removes a key-value pair
containsKey() Checks if a key exists
containsValue() Checks if a value exists
size() Returns the number of key-value pairs
isEmpty() Checks whether the map is empty
clear() Removes all mappings
keySet() Returns all keys
values() Returns all values
entrySet() Returns all key-value pairs

Example 1: Creating a HashMap


import java.util.*;

public class MapExample {

    public static void main(String[] args) {

       Map<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        System.out.println(students);
    }
}

Output

{101=Rahul, 102=Amit, 103=Neha}

Example 2: Retrieving a Value


import java.util.*;

public class GetExample {

    public static void main(String[] args) {

        Map<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");

        System.out.println(students.get(101));
    }
}

Output

Rahul

Example 3: Updating a Value


import java.util.*;

public class UpdateExample {

    public static void main(String[] args) {

        Map<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");

        students.put(101, "Rohan");

        System.out.println(students);
    }
}

Output

{101=Rohan}

The new value replaces the old value because keys must be unique.

Example 4: Removing an Entry


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

       Map<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");

        students.remove(102);

        System.out.println(students);
    }
}

Output

{101=Rahul}

Example 5: Iterating Through a Map


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

        Map students = new HashMap();

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        for(Map.Entry entry : students.entrySet()){

            System.out.println(entry.getKey()
                    + " : "
                    + entry.getValue());
        }
    }
}

Output

101 : Rahul
102 : Amit
103 : Neha

Types of Map Implementations

1. HashMap

Features

  • No guaranteed order
  • Fastest performance
  • Allows one null key
  • Allows multiple null values

Best For

  • General-purpose applications

2. LinkedHashMap

Features

  • Maintains insertion order
  • Slightly slower than HashMap
  • Allows one null key

Best For

  • Ordered data

3. TreeMap

Features

  • Stores keys in sorted order
  • Does not allow null keys
  • Uses a Red-Black Tree

Best For

  • Sorted collections

4. Hashtable

Features

  • Thread-safe
  • Does not allow null keys or values
  • Legacy class

Best For

  • Legacy applications

5. ConcurrentHashMap

Features

  • Thread-safe
  • High concurrency
  • Better performance than Hashtable

Best For

  • Multi-threaded applications

HashMap vs LinkedHashMap vs TreeMap

Feature HashMap LinkedHashMap TreeMap
Ordering No Insertion Order Sorted Order
Null Key Yes Yes No
Null Values Yes Yes Yes
Performance Fastest Fast Slower
Internal Structure Hash Table Hash Table + Linked List Red-Black Tree

Time Complexity

Operation HashMap LinkedHashMap TreeMap
put() O(1) O(1) O(log n)
get() O(1) O(1) O(log n)
remove() O(1) O(1) O(log n)
containsKey() O(1) O(1) O(log n)

Real-life Example

Imagine you’re building a student management system.

Each student has a unique roll number.

Roll Number Students Name
101 Rahul
102 Amit
103 Neha

To retrieve Rahul’s information:


students.get(101);

Output:

Rahul

Other real-world applications include:

  • Employee records
  • Product catalogs
  • User authentication
  • Configuration settings
  • Dictionary applications
  • Inventory management
  • Shopping carts
  • API response caching

Advantages of Java Map

  • Fast data retrieval
  • Unique keys prevent duplicate identifiers
  • Dynamic size
  • Supports Generics
  • Multiple implementations for different use cases
  • Efficient searching
  • Well integrated with the Java Collections Framework
  • Easy iteration using entrySet()

Limitations of Java Map

  • Duplicate keys are not allowed
  • Ordering depends on the implementation
  • Not all implementations are thread-safe
  • TreeMap operations are slower than HashMap
  • Map is not part of the Collection interface

Common Mistakes

1. Expecting Duplicate Keys


map.put(101, "Rahul");
map.put(101, "Amit");

Output:

{101=Amit}

The second value replaces the first one.

2. Assuming HashMap Maintains Order

HashMap does not preserve insertion order.

Use LinkedHashMap if order matters.

3. Using get() Without Checking for Null


System.out.println(map.get(999));

If the key doesn’t exist, null is returned.

A safer approach is:


if(map.containsKey(999)){
    System.out.println(map.get(999));
}

4. Adding Null Keys to TreeMap


Map<Integer, String> Map = new TreeMap<>();

This throws a NullPointerException.

Incorrect:

5. Forgetting Generics


Map map = new HashMap();

Correct:


Map<Integer, String> Map = new TreeMap<>();

Best Practices

  • Program to the Map interface.

Map<Integer, String> students = new TreeMap<>();
  • Use HashMap for maximum performance.
  • Use LinkedHashMap when insertion order is required.
  • Use TreeMap for sorted keys.
  • Use Generics for compile-time type safety.
  • Use containsKey() before calling get() if a key may not exist.
  • Override equals() and hashCode() correctly when using custom objects as keys.

Conclusion

The Java Map interface is one of the most powerful and widely used data structures for storing key-value pairs. It provides fast data retrieval, ensures unique keys, and offers multiple implementations to meet different application requirements.

Related Java Tutorials