0
Explore
0

Map in Java Collection Framework – Complete Guide with Examples

Updated on July 31, 2025

In Java, the Collection Framework is a powerful tool that allows developers to store, manipulate, and retrieve data efficiently. While most collections like List, Set, and Queue store individual elements, the Map interface is unique, it stores data in the form of key-value pairs.

In this tutorial, we will learn every important detail about Map in Java, suitable for beginners and intermediate learners. We’ll break everything down in simple terms and explain with real-world examples.

What is a Map in Java?

In Java, a Map is an object that maps unique keys to corresponding values. It is part of the Java Collection Framework, but unlike List or Set, it does not extend the Collection interface.

We can also define it as, In Java, Map is an interface from the java.util package. It defines the behavior of a mapping data structure, and like all interfaces in Java, it can be used as a type for objects that implement it.

Instead, Map is a separate interface that models a key-value pair data structure—also known as an associative array or dictionary in other programming languages.

Real-world Analogy:

Think of a Map like a dictionary:

  • The word is the key
  • The definition is the value

You can’t have the same word (key) twice in a dictionary, but you can have multiple words with the same definition (value).

Basic Syntax

Map<KeyType, ValueType> mapName = new HashMap<>();

Here, KeyType and ValueType are data types of keys and values, respectively.

Key Characteristics of Map:

FeatureDescription
Duplicates in Keys❌ Not Allowed
Duplicates in Values✅ Allowed
Null Keys✅ Only one null key allowed in HashMap
Null Values✅ Multiple null values are allowed

Implementations of Map Interface

Java provides several classes that implement the Map interface:

Class NameDescription
HashMapFast, unordered map using hashing
LinkedHashMapMaintains insertion order
TreeMapMaintains natural sorted order of keys
HashtableLegacy class, synchronized
ConcurrentHashMapThread-safe version of HashMap

Let’s explore them one by one.

1. HashMap – Most Commonly Used Map

Features:

  • Allows one null key and multiple null values
  • Not thread-safe
  • Does not maintain any order

Example:

import java.util.*;

public class HashMapExample {
    public static void main(String[] args) {
        Map<String, String> capitalMap = new HashMap<>();
        capitalMap.put("India", "New Delhi");
        capitalMap.put("USA", "Washington D.C.");
        capitalMap.put("Japan", "Tokyo");

        System.out.println(capitalMap);
    }
}

Output:

{Japan=Tokyo, USA=Washington D.C., India=New Delhi}

Note: The order may change as HashMap doesn’t guarantee order.

2. LinkedHashMap – Maintains Insertion Order

Features:

  • Keeps the order of keys as inserted
  • Slower than HashMap, but predictable iteration order

Example:

import java.util.*;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> marks = new LinkedHashMap<>();
        marks.put("Math", 90);
        marks.put("Science", 85);
        marks.put("English", 92);

        System.out.println(marks);
    }
}

Output:

{Math=90, Science=85, English=92}

3. TreeMap – Sorted Map

Features:

  • Automatically sorts keys in natural order (ascending for numbers and alphabetic for strings)
  • Does not allow null keys

Example:

import java.util.*;

public class TreeMapExample {
    public static void main(String[] args) {
        Map<Integer, String> tree = new TreeMap<>();
        tree.put(3, "Three");
        tree.put(1, "One");
        tree.put(2, "Two");

        System.out.println(tree);
    }
}

Output:

{1=One, 2=Two, 3=Three}

4. Hashtable – Legacy Synchronized Map

Features:

  • Thread-safe
  • Slower due to synchronization
  • Doesn’t allow null keys or null values

Example:

import java.util.*;

public class HashtableExample {
    public static void main(String[] args) {
        Map<String, String> table = new Hashtable<>();
        table.put("A", "Apple");
        table.put("B", "Banana");

        System.out.println(table);
    }
}

Output

{A=Apple, B=Banana}

5. ConcurrentHashMap – Thread-safe and Fast

Features:

  • Used in multithreading environments
  • Better performance than Hashtable
  • Doesn’t allow null keys or null values
import java.util.concurrent.*;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentMap<String, Integer> cmap = new ConcurrentHashMap<>();
        cmap.put("Java", 90);
        cmap.put("Python", 95);

        System.out.println(cmap);
    }
}

Output

{Java=90, Python=95}

Common Map Methods

MethodDescription
put(key, value)Adds key-value pair
get(key)Returns the value associated with the key
remove(key)Removes entry with the given key
containsKey(key)Checks if key exists
containsValue(value)Checks if value exists
keySet()Returns a set of all keys
values()Returns a collection of all values
entrySet()Returns a set of all key-value pairs

Example with Multiple Methods:

import java.util.*;

public class MapMethodsDemo {
    public static void main(String[] args) {
        Map<String, String> student = new HashMap<>();
        student.put("name", "John");
        student.put("age", "21");
        student.put("course", "B.Tech");

        System.out.println("Name: " + student.get("name"));
        System.out.println("Contains key 'age'? " + student.containsKey("age"));
        System.out.println("All keys: " + student.keySet());
        System.out.println("All values: " + student.values());
        System.out.println("All entries: " + student.entrySet());
    }
}

Example Code Explanation: Using Map Methods

Map<String, String> student = new HashMap<>();

import java.util.*;

public class MapMethodsDemo {
    public static void main(String[] args) {
        Map<String, String> student = new HashMap<>();

Here, we’re creating a Map object named student.

  • It uses String for both keys and values.
  • HashMap is the implementation being used (fast and allows one null key).

put(key, value)

student.put("name", "John");
student.put("age", "21");
student.put("course", "B.Tech");
  • Adds a key-value pair to the map.
  • If the key already exists, its value is replaced.

Internally, the map now looks like this:

{
  "name": "John",
  "age": "21",
  "course": "B.Tech"
}

get(key)

System.out.println("Name: " + student.get("name"));
  • Retrieves the value associated with the given key.
  • In this case, it prints: Name: John

containsKey(key)

System.out.println("Contains key 'age'? " + student.containsKey("age"));
  • Checks if the given key exists in the map.
  • Returns true for "age" since it is present.

keySet()

System.out.println("All keys: " + student.keySet());
  • Returns a Set of all keys in the map.
  • Output: [name, age, course] (order may vary)

values()

System.out.println("All values: " + student.values());
  • Returns a Collection of all values stored in the map.
  • Output: [John, 21, B.Tech] (order may vary)

entrySet()

System.out.println("All entries: " + student.entrySet());
  • Returns a Set of all key-value pairs as Map.Entry objects.
  • Output example: [name=John, age=21, course=B.Tech]

Each entry here is like:

Map.Entry<String, String>

Summary of Map Methods Used:

MethodPurpose
put(k, v)Adds or updates a key-value pair
get(k)Fetches value for the given key
containsKey(k)Checks if the key exists
keySet()Returns all keys
values()Returns all values
entrySet()Returns all key-value pairs

Map vs Collection

FeatureMapCollection (List/Set/Queue)
StoresKey-value pairsSingle elements
Allows duplicateNo (keys)Yes (List), No (Set)
ExamplesHashMap, TreeMapArrayList, HashSet, Queue

Iterating through a Map

Using entrySet() and for-each loop:

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

Using keySet():

for (String key : map.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

Best Practices

  1. Use HashMap for fast, general-purpose usage.
  2. Use LinkedHashMap when order of insertion matters.
  3. Use TreeMap for sorted keys.
  4. Avoid using null keys unless using HashMap.
  5. Use ConcurrentHashMap in multithreaded applications.

Conclusion

The Map interface in Java is extremely powerful when it comes to mapping relationships between data. It is a must-have tool for any serious Java developer. Whether you are building a simple student database, a dictionary, or a configuration system, understanding how different types of maps work will make your code cleaner and more efficient.

Summary Table

Map TypeAllows Null KeyMaintains OrderSortedThread-Safe
HashMap✅ Yes (one)❌ No❌ No❌ No
LinkedHashMap✅ Yes (one)✅ Yes❌ No❌ No
TreeMap❌ No✅ Yes (Sorted)✅ Yes❌ No
Hashtable❌ No❌ No❌ No✅ Yes
ConcurrentHashMap❌ No❌ No❌ No✅ Yes

If you’re learning Java Collections, mastering Map and its implementations is essential. It’s used in real-world applications like caching, storing database records, managing key-value configurations, and much more.