Lesson 4 of 10
Map - HashMap, LinkedHashMap, TreeMap
Map stores key-value pairs - each key maps to exactly one value. It's the most versatile collection: frequency counters, lookup tables, caches, grouping results. HashMap is fastest; LinkedHashMap preserves order; TreeMap keeps keys sorted.
Map API - Complete Reference
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> inventory = new HashMap<>();
// Put & get
inventory.put("Java Book", 10);
inventory.put("Python Book", 5);
inventory.put("Go Book", 8);
inventory.put("Java Book", 15); // overwrites previous value
System.out.println(inventory.get("Python Book")); // 5
System.out.println(inventory.get("Ruby Book")); // null
System.out.println(inventory.getOrDefault("Ruby", 0)); // 0 (safe)
System.out.println(inventory.containsKey("Go Book")); // true
System.out.println(inventory.containsValue(15)); // true
System.out.println(inventory.size()); // 3
// Iterate (three ways)
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.printf("%-15s: %d%n", entry.getKey(), entry.getValue());
}
inventory.forEach((k, v) -> System.out.println(k + " → " + v)); // lambda
inventory.keySet().forEach(System.out::println); // keys only
inventory.values().stream().mapToInt(Integer::intValue).sum(); // sum values
// Compute patterns (very common!)
// putIfAbsent - only adds if key is not present
inventory.putIfAbsent("Rust Book", 3); // adds; would skip if "Java Book"
// computeIfAbsent - compute and store only if key absent (great for grouping)
Map<String, List<String>> byLetter = new HashMap<>();
String[] words = {"Apple", "Avocado", "Banana", "Blueberry"};
for (String word : words) {
byLetter.computeIfAbsent(
String.valueOf(word.charAt(0)), // key = first letter
k -> new ArrayList<>() // create list only if new key
).add(word);
}
System.out.println(byLetter); // {A=[Apple, Avocado], B=[Banana, Blueberry]}
// merge - add or update with a function
inventory.merge("Java Book", 5, Integer::sum); // 15 + 5 = 20
inventory.merge("New Book", 5, Integer::sum); // new key → value = 5
// replaceAll - transform all values
inventory.replaceAll((k, v) -> v * 2); // double all quantities
// Remove
inventory.remove("Go Book");
inventory.remove("Python Book", 9); // remove only if value matches 9
}
}Map Use Cases
- Word frequency counter: map.merge(word, 1, Integer::sum)
- Cache/memoisation: computeIfAbsent for lazy computation
- Grouping by property: computeIfAbsent(key, k -> new ArrayList<>()).add(item)
- Lookup table (enum → handler): Map<Status, Handler>
- Deduplication: put(key, value) - only last value kept per key
- Counting occurrences: getOrDefault(key, 0) + 1
Quick Quiz
Tip
Tip
Practice Map HashMap LinkedHashMap TreeMap in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Map - HashMap, LinkedHashMap, TreeMap
Practice Task
Note
Practice Task - (1) Write a working example of Map HashMap LinkedHashMap TreeMap from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Map HashMap LinkedHashMap TreeMap is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Map stores key-value pairs - each key maps to exactly one value.
- Word frequency counter: map.merge(word, 1, Integer::sum)
- Cache/memoisation: computeIfAbsent for lazy computation
- Grouping by property: computeIfAbsent(key, k -> new ArrayList<>()).add(item)
Finished this lesson?