Map — HashMap, TreeMap, LinkedHashMap

Map — key থেকে value; O(1) গড়ে; তিনটি ভিন্ন guarantees

Read: ~35 min Intermediate 5 practice problems Live code runner

1. What Is a Map?

A Map<K, V> is a collection of unique keys, each associated with one value. Think of a phone directory: a name (key) leads to a number (value). Java provides three main implementations: HashMap for speed, TreeMap for sorted keys, and LinkedHashMap for insertion order.

Map<K, V> হলো unique key-এর সাথে value জুড়ে রাখার collection — যেমন ফোন ডিরেক্টরি: name → number। তিনটি প্রধান implementation: HashMap দ্রুততম, TreeMap sorted, LinkedHashMap insertion order রাখে।

2. HashMap — The O(1) Default

HashMap uses a hash table. put, get, remove, and containsKey are all average O(1). Iteration order is not guaranteed and may change between runs.

HashMap ভেতরে hash table ব্যবহার করে — put/get/remove সবই গড়ে O(1)। কিন্তু iteration-এ order আসে না; run-এ run-এ বদলাতে পারে।
Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Arif", 22);
        ages.put("Rina", 25);
        ages.put("Hasan", 30);

        System.out.println("Rina's age = " + ages.get("Rina"));
        System.out.println("Has Arif? " + ages.containsKey("Arif"));
        System.out.println("Everyone: " + ages);

        // getOrDefault
        int z = ages.getOrDefault("Zakir", -1);
        System.out.println("Zakir age (default): " + z);
    }
}
HashMap — hashCode(key) % capacity → bucket bucket 0 bucket 1 bucket 2 bucket 3 bucket 4 bucket 5 Arif→22 Hasan→30 Rina→25 Average O(1) · Worst O(log n) after Java 8 tree-bins · No guaranteed order Figure 24.1 — hash(key) → bucket; collision হলে Java 8 থেকে bucket-এ tree হয়।

3. TreeMap — Sorted Keys

TreeMap is a Red-Black tree. All operations are O(log n), and iteration returns keys in sorted order. Use it when range queries (firstKey, lastKey, subMap) or natural ordering matters.

TreeMap Red-Black tree-র উপর তৈরি — সব operation O(log n), iteration sorted order-এ হয়। Range query বা sorted output দরকার হলে এটি বেছে নিন।
Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> stock = new TreeMap<>();
        stock.put("Banana", 3);
        stock.put("Apple", 5);
        stock.put("Cherry", 8);
        stock.put("Date", 2);

        System.out.println("in sorted key order: " + stock);
        System.out.println("first key = " + stock.firstKey());
        System.out.println("last key  = " + stock.lastKey());
        System.out.println("A..C subMap: " + stock.subMap("A", "D"));
    }
}

4. LinkedHashMap — Insertion Order

LinkedHashMap is a HashMap that also remembers the order keys were inserted. You get the O(1) operations of HashMap and predictable iteration. It is also the foundation for simple LRU caches.

LinkedHashMap = HashMap + insertion order মনে রাখা। O(1) অপরিবর্তিত; iteration predictable। Simple LRU cache-এর ভিত্তিও এটি।
Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        Map<String, Integer> lm = new LinkedHashMap<>();
        lm.put("one", 1);
        lm.put("two", 2);
        lm.put("three", 3);
        lm.put("four", 4);
        System.out.println("kept insertion order: " + lm);
    }
}

5. Essential Idioms — getOrDefault & computeIfAbsent

Counting occurrences and building multi-maps are the two most common Map patterns. Modern Java has clean one-liners for both.

গণনা (counting) ও multi-map — এই দুই কাজ Map-এ সবচেয়ে বেশি হয়। আধুনিক Java-তে one-liner রয়েছে।
Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        String[] words = { "the", "cat", "sat", "on", "the", "mat", "the", "cat" };

        // Counting with getOrDefault + merge
        Map<String, Integer> counts = new HashMap<>();
        for (String w : words) counts.merge(w, 1, Integer::sum);
        System.out.println("counts = " + counts);

        // Multi-map with computeIfAbsent
        Map<Integer, List<String>> byLen = new HashMap<>();
        for (String w : words) {
            byLen.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
        }
        System.out.println("grouped by length = " + byLen);
    }
}

6. Which Map? — Quick Comparison

NeedUseComplexityবাংলায়
Fastest lookup, order does not matterHashMapO(1) avgDefault পছন্দ।
Keys should iterate in sorted orderTreeMapO(log n)Sorted বা range query।
Insertion-order iterationLinkedHashMapO(1) avgPredictable iteration।
Thread-safe concurrent accessConcurrentHashMapO(1) avgMulti-thread-এ নিরাপদ।
Key invariant: for HashMap/LinkedHashMap, the key class must override equals and hashCode consistently. For TreeMap, the key must be Comparable or you must pass a Comparator.

HashMap-এ key-র equals ও hashCode সঠিকভাবে override করা অত্যন্ত জরুরি। TreeMap-এ key Comparable হতে হবে, নয়তো Comparator দিতে হবে।

7. Practice Problems

  1. Build a HashMap<String, Integer> mapping three students to their marks, then print marks for one student.
    তিন জন ছাত্রের নাম ও নম্বরের একটি HashMap বানিয়ে একজনের নম্বর প্রিন্ট করুন।
    ✨ Show Answer
    Main.java
    import java.util.*;
    class Main {
        public static void main(String[] args) {
            Map<String, Integer> marks = new HashMap<>();
            marks.put("Arif", 88);
            marks.put("Rina", 92);
            marks.put("Hasan", 76);
            System.out.println("Rina = " + marks.get("Rina"));
        }
    }
  2. Count word frequencies in the sentence "the cat sat on the mat".
    "the cat sat on the mat" বাক্যে প্রতিটি শব্দ কতবার এসেছে গুনুন।
    ✨ Show Answer
    Main.java
    import java.util.*;
    class Main {
        public static void main(String[] args) {
            String[] ws = "the cat sat on the mat".split(" ");
            Map<String, Integer> c = new HashMap<>();
            for (String w : ws) c.merge(w, 1, Integer::sum);
            System.out.println(c);
        }
    }
  3. Print the keys of a TreeMap in sorted order, plus its firstKey and lastKey.
    TreeMap-এর key-গুলো sorted order-এ এবং প্রথম/শেষ key প্রিন্ট করুন।
    ✨ Show Answer
    Main.java
    import java.util.*;
    class Main {
        public static void main(String[] args) {
            TreeMap<String, Integer> t = new TreeMap<>();
            t.put("delta", 4);
            t.put("alpha", 1);
            t.put("charlie", 3);
            t.put("bravo", 2);
            System.out.println(t.keySet());
            System.out.println("first = " + t.firstKey() + ", last = " + t.lastKey());
        }
    }
  4. Explain why overriding equals without hashCode breaks HashMap.
    hashCode ছাড়া শুধু equals override করলে HashMap কেন ভেঙে যায়?
    ✨ Show Answer

    Answer: HashMap locates a key by computing hashCode() first (to find the bucket), then uses equals() inside that bucket to find the exact entry. If two equal objects return different hash codes, they land in different buckets and the Map treats them as distinct keys — put followed by get returns null. The contract is: equal objects must have equal hash codes.

    HashMap প্রথমে hashCode() দিয়ে bucket খোঁজে, তারপর সেই bucket-এ equals() দিয়ে মিল দেখে। দুটি equal object যদি আলাদা hashCode দেয়, তারা আলাদা bucket-এ যাবে — Map তাদের আলাদা key মনে করবে; put-এর পর get দিলে null। Contract: equal হলে hashCode-ও equal হতে হবে।

  5. Group a list of words by their length using computeIfAbsent.
    computeIfAbsent দিয়ে কিছু শব্দকে length অনুযায়ী group করুন।
    ✨ Show Answer
    Main.java
    import java.util.*;
    class Main {
        public static void main(String[] args) {
            String[] ws = { "go", "do", "cat", "dog", "tree", "bird" };
            Map<Integer, List<String>> g = new HashMap<>();
            for (String w : ws) {
                g.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
            }
            System.out.println(g);
        }
    }

Summary — Module 24

Map<K,V> ties unique keys to values. HashMap is the default O(1) choice; TreeMap gives sorted keys at O(log n); LinkedHashMap preserves insertion order. Master the idioms getOrDefault, merge, and computeIfAbsent — they replace most hand-written if-else on Maps.

Map হলো key → value। HashMap O(1) default, TreeMap sorted key O(log n), LinkedHashMap insertion order রাখে। getOrDefault, merge, computeIfAbsent — এই তিনটি idiom শিখলে Map-এর 80% কাজ এক লাইনেই হয়ে যাবে।

Next Module → Set — HashSet, TreeSet, LinkedHashSet।