JAVA - Zero to Hero / Collection Framework

Map Interface

The Map interface is part of the Java Collections Framework, but unlike List and Set, it does not extend the Collection interface. A Map stores data in key-value pairs, where each key is unique, and each key maps to exactly one value.


🧩 Key Features of Map:

  • Stores key-value pairs

  • Keys are unique, but values can be duplicated

  • Allows one null key and multiple null values (in some implementations)

  • Provides fast lookup using keys


🔧 Common Implementations

Class

Order Maintained?

Sorted?

Null Support

HashMap

❌ No

❌ No

✅ 1 null key, many null values

TreeMap

❌ Based on sorted keys

✅ Yes (ascending)

❌ No null key

LinkedHashMap

✅ Yes (insertion order)

❌ No

✅ 1 null key


✅ Example 1: HashMap

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("Apple", 3);
        map.put("Banana", 5);
        map.put("Mango", 2);
        map.put("Banana", 6);  // Overwrites previous value

        System.out.println(map);
    }
}
{Apple=3, Banana=6, Mango=2}Note: Order is not guaranteed in HashMap.

✅ Example 2: TreeMap

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();

        map.put(3, "Banana");
        map.put(1, "Apple");
        map.put(2, "Mango");

        System.out.println(map);
    }
}
{1=Apple, 2=Mango, 3=Banana}

Keys are automatically sorted in ascending order.


✅ Example 3: LinkedHashMap

import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        System.out.println(map);
    }
}
{One=1, Two=2, Three=3}

Maintains insertion order.


🔧 Common Methods in Map

Method

Description

put(key, value)

Adds or updates a key-value pair

get(key)

Returns value for the given key

remove(key)

Removes entry with the given key

containsKey(key)

Checks if key exists

containsValue(value)

Checks if value exists

keySet()

Returns set of all keys

values()

Returns collection of all values

entrySet()

Returns set of key-value pairs (Map.Entry)


🧠 Use Cases of Map

  • Storing student ID → name

  • Creating dictionary or glossary

  • Mapping URLs → page titles

  • Implementing caching mechanisms


⚖️ HashMap vs TreeMap vs LinkedHashMap

Feature

HashMap

TreeMap

LinkedHashMap

Ordering

Unordered

Sorted by key

Insertion Order

Null Key Allowed

✅ Yes

❌ No

✅ Yes

Performance

⚡ Fast (O(1))

⏳ Slower (O(log n))

⚡ Fast (slightly slower than HashMap)

Use Case

General purpose

Sorted data needed

Ordered iteration