Map — HashMap, TreeMap, LinkedHashMap
Map — key থেকে value; O(1) গড়ে; তিনটি ভিন্ন guarantees
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-এ বদলাতে পারে।
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);
}
}
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 দরকার হলে এটি বেছে নিন।
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-এর ভিত্তিও এটি।
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.
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
| Need | Use | Complexity | বাংলায় |
|---|---|---|---|
| Fastest lookup, order does not matter | HashMap | O(1) avg | Default পছন্দ। |
| Keys should iterate in sorted order | TreeMap | O(log n) | Sorted বা range query। |
| Insertion-order iteration | LinkedHashMap | O(1) avg | Predictable iteration। |
| Thread-safe concurrent access | ConcurrentHashMap | O(1) avg | Multi-thread-এ নিরাপদ। |
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
-
Build a
HashMap<String, Integer>mapping three students to their marks, then print marks for one student.তিন জন ছাত্রের নাম ও নম্বরের একটিHashMapবানিয়ে একজনের নম্বর প্রিন্ট করুন।✨ Show Answer
Main.javaimport 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")); } } -
Count word frequencies in the sentence
"the cat sat on the mat"."the cat sat on the mat"বাক্যে প্রতিটি শব্দ কতবার এসেছে গুনুন।✨ Show Answer
Main.javaimport 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); } } -
Print the keys of a TreeMap in sorted order, plus its
firstKeyandlastKey.TreeMap-এর key-গুলো sorted order-এ এবং প্রথম/শেষ key প্রিন্ট করুন।✨ Show Answer
Main.javaimport 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()); } } -
Explain why overriding
equalswithouthashCodebreaksHashMap.hashCodeছাড়া শুধুequalsoverride করলেHashMapকেন ভেঙে যায়?✨ Show Answer
Answer: HashMap locates a key by computing
hashCode()first (to find the bucket), then usesequals()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 —putfollowed bygetreturnsnull. 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 হতে হবে। -
Group a list of words by their length using
computeIfAbsent.computeIfAbsentদিয়ে কিছু শব্দকে length অনুযায়ী group করুন।✨ Show Answer
Main.javaimport 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.
getOrDefault, merge, computeIfAbsent — এই তিনটি idiom শিখলে Map-এর 80% কাজ এক লাইনেই হয়ে যাবে।