Skip to main content

Java Collections

HashMap / TreeMap

Complete lesson for HashMap / TreeMap using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — HashMap / TreeMap

Section: Java Collections. HashMap stores data as key-value pairs with super-fast lookups. Learn put, get, update, remove, counting, grouping, custom keys, LinkedHashMap, TreeMap, Hashtable, internals, collisions, LRU cache, and ConcurrentHashMap — all with real-life examples.

What is HashMap?

  • HashMap<K, V> is a Map implementation in java.util that stores data as key-value pairs. Each key is unique and points to exactly one value.
  • You find a value by its key, not by position. put, get, and remove take O(1) time on average, even with millions of entries.
  • Putting a value under an existing key replaces the old value. Values can repeat; keys cannot.
  • Real life: the contacts app on your phone. You search by name (key) and get the phone number (value). Saving the same name again updates the number.
import java.util.HashMap;
import java.util.Map;

public class PhoneBook {
    public static void main(String[] args) {
        Map<String, String> contacts = new HashMap<>();     // name -> phone number
        contacts.put("Mom", "98480 11111");
        contacts.put("Ravi", "90000 22222");
        contacts.put("Office", "040 2345 6789");

        System.out.println("Call Mom: " + contacts.get("Mom"));             // 98480 11111
        contacts.put("Ravi", "91111 33333");                                // same key: number updated
        System.out.println("Ravi now: " + contacts.get("Ravi"));            // 91111 33333
        System.out.println("Has Asha? " + contacts.containsKey("Asha"));    // false
        System.out.println("Total contacts: " + contacts.size());           // 3
    }
}

Real-life examples of HashMap

Real-life scenarioKeyValueWhy a HashMap
Phone contactsNamePhone numberInstant lookup by name
Dictionary appWordMeaningFind any word in O(1)
Shopping cartProduct IDQuantityUpdate quantity of one product quickly
Bank systemAccount numberBalanceFetch and update a balance directly
Railway reservationPNR numberBooking detailsCheck status with one key
RTO vehicle registryVehicle numberOwner detailsTrace the owner of a number plate
Election countingCandidateVote countIncrement the right counter for every vote
Student reportRoll numberMarksTeacher looks up marks by roll number
Browser cacheURLSaved pageServe a page without downloading again
Login systemSession tokenLogged-in userIdentify the user on every request
Country quizCountryCapitalCheck an answer instantly
Restaurant menuDishPriceCalculate the bill item by item

Features of HashMap

FeatureMeaning
Key-value pairsEvery entry is a key mapped to a value
Unique keysSame key again replaces the value (decided by equals and hashCode)
Duplicate valuesAllowed: two students can have the same marks
nullOne null key and any number of null values
No orderIteration order is unpredictable and can change after resizing
SpeedAverage O(1) for put, get, remove, containsKey
DefaultsCapacity 16, load factor 0.75
Thread-safeNo (use ConcurrentHashMap for threads)
IteratorFail-fast: modifying the map while looping throws ConcurrentModificationException
InterfacesMap, Cloneable, Serializable (not Collection)

Creating a HashMap

Constructor or factoryMeaning
new HashMap<>()Empty map, capacity 16, load factor 0.75
new HashMap<>(int capacity)Empty map with a given starting capacity
new HashMap<>(int capacity, float loadFactor)Custom capacity and load factor
new HashMap<>(Map m)Mutable copy of another map
HashMap.newHashMap(int n) (Java 19)Sized to hold n entries without resizing
Map.of(k1, v1, k2, v2) (Java 9)Immutable map, not a HashMap; wrap in new HashMap<>(...) to edit
import java.util.HashMap;
import java.util.Map;

public class CreateHashMap {
    public static void main(String[] args) {
        Map<String, Integer> a = new HashMap<>();                                // default: 16, 0.75
        Map<String, Integer> b = new HashMap<>(200);                             // expecting ~150 entries
        Map<String, Integer> c = new HashMap<>(64, 0.5f);                        // custom load factor
        Map<String, Integer> d = new HashMap<>(Map.of("apple", 120, "mango", 80)); // mutable copy
        Map<String, Integer> e = HashMap.newHashMap(1000);                       // Java 19: room for 1000

        a.put("tea", 15);
        d.put("banana", 40);                       // allowed: d is a real HashMap
        System.out.println(a.size() + " " + b.size() + " " + c.size() + " " + d.size() + " " + e.size());
        // 1 0 0 3 0
    }
}

HashMap methods

MethodWhat it doesReal-life use
put(k, v)Adds or replaces; returns the old value or nullSave a contact number
putAll(m)Copies all entries from another mapMerge two price lists
get(k)Value for the key, or null if absentLook up a PNR booking
getOrDefault(k, d)Value, or the default if the key is absentPrice of a dish, 0 if not on the menu
containsKey(k)True if the key existsIs this username taken?
containsValue(v)True if any key maps to the value (O(n))Did anyone score 100?
remove(k)Removes the entry; returns the old valueDelete a contact
remove(k, v)Removes only if the key maps to that valueCancel a seat only if it is still yours
replace(k, v)Replaces only if the key existsUpdate stock of an existing product
putIfAbsent(k, v)Adds only if the key is missingRegister a username only once
computeIfAbsent(k, f)Creates the value with f if missing, returns itCreate a department list on first employee
computeIfPresent(k, f)Recomputes the value only if presentApply a discount to an existing item
compute(k, f)Recomputes the value whether present or notUpdate a running score
merge(k, v, f)Puts v if absent, else combines old and v with fCount votes per candidate
keySet()View of all keysList of all registered usernames
values()View of all valuesSum of all account balances
entrySet()View of all key-value pairsPrint a report card
forEach(f)Runs f for each key and valueSend a reminder to every member
replaceAll(f)Replaces every value using fAdd 18% GST to every price
size() / isEmpty()Number of entries / true if noneItems in cart / is the cart empty?
clear()Removes all entriesEmpty the cart after checkout

Adding, updating, and removing entries

  • put returns the previous value (or null), so you can tell whether it was an add or an update.
  • putIfAbsent adds only new keys, replace changes only existing keys, and merge adds or combines in one call.
  • remove(key, value) removes only when the current value matches — a safe conditional delete.
  • Real life: an online grocery cart where the customer adds items, taps + and −, and removes products.
import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {
    public static void main(String[] args) {
        Map<String, Integer> cart = new HashMap<>();   // product -> quantity

        cart.put("Milk", 2);
        cart.put("Bread", 1);
        Integer old = cart.put("Milk", 3);             // update: returns previous value
        System.out.println("Milk was " + old + ", now " + cart.get("Milk"));   // Milk was 2, now 3

        cart.putIfAbsent("Bread", 5);                  // ignored: Bread already in cart
        cart.putIfAbsent("Eggs", 12);                  // added
        cart.replace("Eggs", 6);                       // replaces because Eggs exists
        cart.replace("Butter", 1);                     // ignored: Butter not in cart

        cart.merge("Bread", 1, Integer::sum);          // customer taps + on Bread: 1 -> 2
        cart.remove("Milk");                           // customer removes milk
        boolean removed = cart.remove("Eggs", 12);     // only if quantity is 12: false

        System.out.println("Bread: " + cart.get("Bread") + ", Eggs: " + cart.get("Eggs") + ", removed eggs? " + removed);
        // Bread: 2, Eggs: 6, removed eggs? false
        System.out.println("Items in cart: " + cart.size());   // 2
    }
}

Reading values safely

  • get returns null for a missing key — and also for a key whose value is null. Use containsKey when you must tell them apart.
  • getOrDefault gives a fallback only when the key is absent, not when the stored value is null.
  • Unboxing trap: int price = map.get("Juice"); throws NullPointerException when the key is missing.
  • Real life: a tea stall billing counter looking up prices for each ordered item.
import java.util.HashMap;
import java.util.Map;

public class PriceLookup {
    public static void main(String[] args) {
        Map<String, Double> prices = new HashMap<>();
        prices.put("Tea", 15.0);
        prices.put("Coffee", 25.0);
        prices.put("Samosa", null);                               // price not decided yet

        System.out.println(prices.get("Tea"));                    // 15.0
        System.out.println(prices.get("Juice"));                  // null: no such key
        System.out.println(prices.get("Samosa"));                 // null: key exists, value is null

        System.out.println(prices.containsKey("Juice"));          // false
        System.out.println(prices.containsKey("Samosa"));         // true
        System.out.println(prices.getOrDefault("Juice", 0.0));    // 0.0
        System.out.println(prices.getOrDefault("Samosa", 0.0));   // null: the key exists

        double bill = 0;
        for (String item : new String[] { "Tea", "Coffee", "Juice" }) {
            Double p = prices.get(item);
            if (p == null) {
                System.out.println(item + " is not on the menu");
                continue;
            }
            bill += p;
        }
        System.out.println("Bill: " + bill);                      // 40.0
    }
}

Iterating a HashMap

  • Avoid for (k : keySet()) map.get(k) — it does a second lookup per key. Use entrySet() instead.
  • Never call map.remove inside a for-each loop; it throws ConcurrentModificationException. Use Iterator.remove or removeIf.
  • Real life: a class teacher printing a report card, finding the average, and removing failed students from a toppers list.
WayGives youBest for
entrySet() loopKey and value togetherMost loops (fastest, one lookup)
keySet() loopOnly keysWhen values are not needed
values() loopOnly valuesTotals and averages
forEach((k, v) -> ...)Key and valueShort, readable code
Iterator on entrySet()Key and value with remove()Removing while looping
removeIf on a viewCondition-based removalOne-line cleanup
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ReportCard {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Anil", 82);
        marks.put("Bhavya", 95);
        marks.put("Chitra", 34);
        marks.put("Dev", 67);

        // 1. entrySet: key and value together (best)
        for (Map.Entry<String, Integer> e : marks.entrySet()) {
            System.out.println(e.getKey() + " scored " + e.getValue());
        }

        // 2. keySet: only names
        System.out.println("Students: " + marks.keySet());

        // 3. values: only marks
        int total = 0;
        for (int m : marks.values()) total += m;
        System.out.println("Class average: " + total / marks.size());      // 69

        // 4. forEach with a lambda
        marks.forEach((name, m) -> System.out.println(name + (m >= 35 ? " passed" : " failed")));

        // 5. Iterator: safe removal while looping
        Iterator<Map.Entry<String, Integer>> it = marks.entrySet().iterator();
        while (it.hasNext()) {
            if (it.next().getValue() < 35) it.remove();
        }
        // same in one line: marks.values().removeIf(m -> m < 35);
        System.out.println("Passed students: " + marks.size());             // 3
    }
}

Counting with HashMap

  • Counting is the most common HashMap job: key = the thing, value = how many times it appeared.
  • Three styles: put(k, getOrDefault(k, 0) + 1), merge(k, 1, Integer::sum) (shortest), and compute(k, (key, v) -> v == null ? 1 : v + 1).
  • Real life: counting votes for each candidate in a class election and announcing the winner.
import java.util.HashMap;
import java.util.Map;

public class VoteCounter {
    public static void main(String[] args) {
        String[] votes = { "Asha", "Ravi", "Asha", "Meena", "Ravi", "Asha", "Meena", "Asha" };

        Map<String, Integer> count = new HashMap<>();
        for (String v : votes) {
            count.put(v, count.getOrDefault(v, 0) + 1);      // style 1
        }

        Map<String, Integer> count2 = new HashMap<>();
        for (String v : votes) {
            count2.merge(v, 1, Integer::sum);                // style 2 (shortest)
        }

        String winner = null;
        int max = 0;
        for (Map.Entry<String, Integer> e : count.entrySet()) {
            if (e.getValue() > max) {
                max = e.getValue();
                winner = e.getKey();
            }
        }
        System.out.println("Asha: " + count.get("Asha") + ", Ravi: " + count.get("Ravi") + ", Meena: " + count.get("Meena"));
        // Asha: 4, Ravi: 2, Meena: 2
        System.out.println("Winner: " + winner + " with " + max + " votes");   // Winner: Asha with 4 votes
        System.out.println("Both styles agree: " + count.equals(count2));      // true
    }
}

Grouping with computeIfAbsent

  • To group items, use a map whose value is a list: Map<String, List<String>>.
  • computeIfAbsent(key, k -> new ArrayList<>()) creates the list the first time a key appears and returns the existing list after that — so .add(item) always works.
  • Old way (longer): check containsKey, create and put an empty list, then get(key).add(item).
  • Real life: HR grouping employees by department for a seating plan.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DepartmentGroups {
    public static void main(String[] args) {
        String[][] employees = {
            { "Kiran", "IT" }, { "Lata", "HR" }, { "Manoj", "IT" },
            { "Nisha", "Sales" }, { "Omkar", "IT" }, { "Pooja", "HR" }
        };

        Map<String, List<String>> byDept = new HashMap<>();
        for (String[] e : employees) {
            byDept.computeIfAbsent(e[1], d -> new ArrayList<>()).add(e[0]);
        }

        System.out.println("IT: " + byDept.get("IT"));          // IT: [Kiran, Manoj, Omkar]
        System.out.println("HR: " + byDept.get("HR"));          // HR: [Lata, Pooja]
        System.out.println("Sales: " + byDept.get("Sales"));    // Sales: [Nisha]
        System.out.println("Departments: " + byDept.size());    // 3
    }
}

HashMap with custom keys

  • When a key is your own class, HashMap uses its hashCode to find the bucket and equals to match the key. Both must be overridden using the same fields.
  • A record generates correct equals and hashCode automatically and is immutable — the ideal key.
  • Real life: a cinema booking system where a seat (row + number) maps to the customer who booked it.
import java.util.HashMap;
import java.util.Map;

public class CinemaBooking {
    record Seat(char row, int number) { }      // record = correct equals and hashCode for free

    public static void main(String[] args) {
        Map<Seat, String> booked = new HashMap<>();
        booked.put(new Seat('F', 12), "Arjun");
        booked.put(new Seat('F', 13), "Divya");

        Seat wanted = new Seat('F', 12);       // a different object with the same row and number
        if (booked.containsKey(wanted)) {
            System.out.println("F12 already booked by " + booked.get(wanted));     // Arjun
        }

        String previous = booked.putIfAbsent(new Seat('F', 12), "Kavya");
        System.out.println("Kavya got the seat? " + (previous == null));          // false
        System.out.println("Seats booked: " + booked.size());                     // 2
    }
}

Differences between HashMap, LinkedHashMap, and TreeMap

FeatureHashMapLinkedHashMapTreeMap
Order of keysNo orderInsertion order (or access order)Sorted by key
Internal structureHash tableHash table + doubly linked listRed-black tree
put / get / removeO(1) averageO(1) averageO(log n)
null keyOne allowedOne allowedNot allowed (natural ordering)
null valuesAllowedAllowedAllowed
Key requirementequals + hashCodeequals + hashCodeComparable or a Comparator
MemoryLowestMore (links)More (tree nodes)
Extra featuresNoneLRU cache via access orderfloorKey, ceilingKey, subMap, headMap
Real-life usePhone contactsRestaurant order queueTrain timetable sorted by time
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class ThreeMaps {
    public static void main(String[] args) {
        String[] cities = { "Pune", "Delhi", "Agra", "Mumbai" };
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        Map<String, Integer> tree = new TreeMap<>();

        for (String c : cities) {
            hash.put(c, c.length());
            linked.put(c, c.length());
            tree.put(c, c.length());
        }
        System.out.println("HashMap:       " + hash);     // hash-based order, not predictable
        System.out.println("LinkedHashMap: " + linked);   // {Pune=4, Delhi=5, Agra=4, Mumbai=6}
        System.out.println("TreeMap:       " + tree);     // {Agra=4, Delhi=5, Mumbai=6, Pune=4}
    }
}

LinkedHashMap: insertion order

  • LinkedHashMap is a HashMap that also remembers the order in which keys were first inserted. Same O(1) speed, slightly more memory.
  • Updating an existing key does not move it; removing and re-inserting puts it at the end.
  • Java 21 adds firstEntry(), lastEntry(), and pollFirstEntry() because LinkedHashMap is a SequencedMap.
  • Real life: a restaurant kitchen that must cook orders in the order the tables placed them.
import java.util.LinkedHashMap;
import java.util.Map;

public class KitchenTickets {
    public static void main(String[] args) {
        Map<Integer, String> orders = new LinkedHashMap<>();   // table number -> dish
        orders.put(7, "Paneer Tikka");
        orders.put(2, "Veg Biryani");
        orders.put(5, "Masala Dosa");
        orders.put(7, "Paneer Tikka + Naan");                  // update: table 7 stays first

        System.out.println(orders);
        // {7=Paneer Tikka + Naan, 2=Veg Biryani, 5=Masala Dosa}

        Map.Entry<Integer, String> next = orders.entrySet().iterator().next();
        System.out.println("Cook first: table " + next.getKey() + " - " + next.getValue());
        // Cook first: table 7 - Paneer Tikka + Naan
    }
}

TreeMap: sorted keys and range queries

  • TreeMap keeps keys sorted (natural order or a Comparator) and answers "nearest key" questions that HashMap cannot.
  • Operations take O(log n). Keys must be comparable, and a null key is not allowed.
  • Real life: converting marks to a grade with floorEntry, and finding the next train after a given time with ceilingEntry.
MethodReturnsTrain timetable example
firstKey() / lastKey()Smallest / largest keyFirst and last train of the day
floorKey(k)Largest key ≤ kLast train at or before 10:00
ceilingKey(k)Smallest key ≥ kNext train at or after 10:00
lowerKey(k) / higherKey(k)Strictly < k / strictly > kTrain just before / just after a time
headMap(k)Keys < kAll morning trains (before 12:00)
tailMap(k)Keys ≥ kAll trains from 12:00 onwards
subMap(a, b)Keys from a (inclusive) to b (exclusive)Trains between 09:00 and 14:00
pollFirstEntry()Removes and returns the first entryRemove a train once it departs
descendingMap()Reverse-ordered viewTimetable from latest to earliest
import java.util.TreeMap;

public class GradesAndTrains {
    public static void main(String[] args) {
        TreeMap<Integer, String> grade = new TreeMap<>();     // minimum marks -> grade
        grade.put(0, "F");
        grade.put(35, "C");
        grade.put(60, "B");
        grade.put(75, "A");
        grade.put(90, "A+");
        for (int m : new int[] { 92, 74, 35, 12 }) {
            System.out.println(m + " -> " + grade.floorEntry(m).getValue());
        }
        // 92 -> A+, 74 -> B, 35 -> C, 12 -> F

        TreeMap<String, String> trains = new TreeMap<>();     // departure time -> train
        trains.put("06:15", "Shatabdi");
        trains.put("09:40", "Intercity");
        trains.put("13:05", "Express");
        trains.put("18:30", "Rajdhani");

        System.out.println("Next after 10:00: " + trains.ceilingEntry("10:00"));    // 13:05=Express
        System.out.println("Last before 10:00: " + trains.floorEntry("10:00"));     // 09:40=Intercity
        System.out.println("Morning trains: " + trains.headMap("12:00"));           // {06:15=Shatabdi, 09:40=Intercity}
        System.out.println("First " + trains.firstKey() + ", last " + trains.lastKey());   // First 06:15, last 18:30
    }
}

Differences between HashMap and Hashtable

FeatureHashMapHashtable
IntroducedJava 1.2 (Collections Framework)Java 1.0 (legacy)
Thread-safeNoYes (every method synchronized)
SpeedFastSlower due to locking
null key / valuesOne null key, many null valuesNeither allowed (NullPointerException)
IterationFail-fast IteratorEnumeration (not fail-fast) and Iterator
Parent classAbstractMapDictionary
Default capacity1611
Modern replacement—ConcurrentHashMap for threads
Use todayYes, everywhereNo, only in old code
L2

Advanced — HashMap / TreeMap

How HashMap works internally

  • A HashMap is an array of buckets (called the table). Each bucket holds nodes, and each node stores hash, key, value, and next.
  • The key is converted to a bucket number, so HashMap jumps straight to one bucket instead of scanning everything.
  • Real life: a railway cloak room. The attendant turns your token number into a rack number, walks straight to that rack, then matches your exact token among the few bags kept there.
StepWhat put(key, value) doesCloak room analogy
1Calls key.hashCode()Read the token number
2Spreads the bits: h ^ (h >>> 16)Mix the digits so racks fill evenly
3Bucket index = (n - 1) & hash (n = table size)Work out the rack number
4Empty bucket: store a new node thereEmpty rack: keep the bag
5Otherwise walk the bucket; if equals matches, replace the value and return the old oneSame token found: swap the bag
6No match: append a node (list) or insert into a tree binDifferent token: add the bag to the rack
7Increase size; resize if size > capacity × load factorRacks too full: move to a bigger room
public class BucketDemo {
    static int bucketOf(Object key, int capacity) {
        int h = key.hashCode();
        int spread = h ^ (h >>> 16);             // mixes high bits into low bits
        return (capacity - 1) & spread;          // fast modulo because capacity is a power of 2
    }

    public static void main(String[] args) {
        String[] keys = { "Aa", "BB", "apple", "mango", "kiwi" };
        for (String k : keys) {
            System.out.println(k + " hash=" + k.hashCode() + " bucket=" + bucketOf(k, 16));
        }
        // "Aa" and "BB" both have hashCode 2112, so they land in the same bucket: a collision.
        // get() walks that bucket and uses equals() to pick the right key.
    }
}

Capacity, load factor, and resizing

  • Capacity is the number of buckets (always a power of 2). Load factor (default 0.75) decides how full the table gets before it grows.
  • Threshold = capacity × load factor. When size exceeds it, the table doubles and every entry is moved (rehashed) — an O(n) step.
  • If you know the size in advance, pre-size the map to skip all resizes: HashMap.newHashMap(n) (Java 19) or new HashMap<>((int) (n / 0.75f) + 1).
  • Real life: a wedding caterer who books a hall for the expected guest count instead of shifting halls three times during the event.
Entries addedCapacityThreshold (× 0.75)What happens
0 to 121612No resize
13th entry16 → 3224First resize: all entries rehashed
25th entry32 → 6448Second resize
49th entry64 → 12896Third resize
97th entry128 → 256192Fourth resize
Pre-sized for 100256 from the start192Zero resizes
import java.util.HashMap;
import java.util.Map;

public class PreSizing {
    public static void main(String[] args) {
        int n = 1_000_000;

        long t1 = System.nanoTime();
        Map<Integer, Integer> grow = new HashMap<>();             // resizes about 17 times
        for (int i = 0; i < n; i++) grow.put(i, i);
        long t2 = System.nanoTime();

        Map<Integer, Integer> sized = HashMap.newHashMap(n);      // Java 19: no resizes
        for (int i = 0; i < n; i++) sized.put(i, i);
        long t3 = System.nanoTime();

        System.out.println("Growing map:  " + (t2 - t1) / 1_000_000 + " ms");
        System.out.println("Pre-sized map: " + (t3 - t2) / 1_000_000 + " ms");   // usually faster
    }
}

Collisions and treeification

  • A collision happens when two different keys land in the same bucket. HashMap keeps them in a linked list and uses equals to tell them apart.
  • Since Java 8, a bucket with too many nodes is converted into a red-black tree, so the worst case becomes O(log n) instead of O(n).
  • Tree bins work best when keys are Comparable (like String and Integer).
  • Real life: a school register drawer labelled "R" that gets crowded with many students named Rahul — once it is too full, the clerk sorts it so finding one Rahul stays quick.
ConstantValueMeaning
TREEIFY_THRESHOLD8A bucket list longer than this becomes a tree
UNTREEIFY_THRESHOLD6A tree smaller than this (after resize) becomes a list again
MIN_TREEIFY_CAPACITY64Below this table size, HashMap resizes instead of treeifying
Worst case before Java 8O(n)All keys in one long list
Worst case since Java 8O(log n)All keys in one balanced tree
import java.util.HashMap;
import java.util.Map;

public class CollisionDemo {
    record GoodKey(int id) { }

    static final class BadKey {
        final int id;
        BadKey(int id) { this.id = id; }
        @Override public boolean equals(Object o) { return o instanceof BadKey b && b.id == id; }
        @Override public int hashCode() { return 42; }          // every key collides
    }

    public static void main(String[] args) {
        int n = 10_000;

        long t1 = System.nanoTime();
        Map<GoodKey, Integer> good = new HashMap<>();
        for (int i = 0; i < n; i++) good.put(new GoodKey(i), i);
        long t2 = System.nanoTime();

        Map<BadKey, Integer> bad = new HashMap<>();
        for (int i = 0; i < n; i++) bad.put(new BadKey(i), i);
        long t3 = System.nanoTime();

        System.out.println("Good keys: " + (t2 - t1) / 1_000_000 + " ms");
        System.out.println("Bad keys:  " + (t3 - t2) / 1_000_000 + " ms (all in one bucket)");
        System.out.println(bad.get(new BadKey(9_999)));         // 9999: still correct, just slow
    }
}

equals and hashCode contract for keys

  • Real life: an office ID card system. Two cards printed with the same employee code must open the same profile — that only works if both methods agree.
RuleWhat goes wrong if broken
Equal objects must have equal hash codesget searches the wrong bucket and returns null
Override equals and hashCode togetherDuplicate keys appear; lookups fail
Use the same fields in both methodsKeys that are equal end up in different buckets
Unequal objects may share a hash codeAllowed (a collision), but too many slow the map down
hashCode must not change while the key is in the mapThe entry is lost (see the next section)
Prefer records or Objects.hash(fields)Hand-written code is easy to get wrong
import java.util.HashMap;
import java.util.Map;

public class KeyContract {
    static class BadEmpId {                      // equals only, no hashCode
        final String code;
        BadEmpId(String code) { this.code = code; }
        @Override public boolean equals(Object o) {
            return o instanceof BadEmpId other && other.code.equals(code);
        }
    }

    record EmpId(String code) { }                // record: equals and hashCode generated

    public static void main(String[] args) {
        Map<BadEmpId, String> bad = new HashMap<>();
        bad.put(new BadEmpId("E101"), "Sita");
        System.out.println(bad.get(new BadEmpId("E101")));    // null (almost always): different hashCode

        Map<EmpId, String> good = new HashMap<>();
        good.put(new EmpId("E101"), "Sita");
        System.out.println(good.get(new EmpId("E101")));      // Sita
    }
}

Mutable keys: the lost entry trap

  • HashMap stores the hash of a key when it is inserted. If you later change a field used in hashCode, the map looks in the wrong bucket and can never find the entry again.
  • The entry still counts in size() and occupies memory — a silent memory leak.
  • Fix: use immutable keys (String, Integer, records with final fields). If a key must change, remove it, change it, and put it back.
  • Real life: a gym locker register keyed by locker number. If someone repaints the number on the locker key, the register can no longer find the owner.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class LostEntry {
    static class Locker {
        String number;                                         // mutable: dangerous as a key
        Locker(String number) { this.number = number; }
        @Override public boolean equals(Object o) { return o instanceof Locker l && l.number.equals(number); }
        @Override public int hashCode() { return Objects.hash(number); }
    }

    public static void main(String[] args) {
        Map<Locker, String> owners = new HashMap<>();
        Locker locker = new Locker("L-10");
        owners.put(locker, "Farhan");

        locker.number = "L-99";                                // key changed while inside the map
        System.out.println(owners.get(locker));                // null: wrong bucket
        System.out.println(owners.containsKey(new Locker("L-10")));   // false: equals now fails
        System.out.println(owners.size());                     // 1: entry stuck forever
    }
}

Time complexity of HashMap, LinkedHashMap, and TreeMap

OperationHashMapLinkedHashMapTreeMapConcurrentHashMap
putO(1) avgO(1) avgO(log n)O(1) avg
get / containsKeyO(1) avgO(1) avgO(log n)O(1) avg
removeO(1) avgO(1) avgO(log n)O(1) avg
containsValueO(n)O(n)O(n)O(n)
Iterate all entriesO(capacity + n)O(n)O(n)O(capacity + n)
First / last keyNot supportedO(1) (Java 21)O(log n)Not supported
Worst case lookupO(log n) (tree bins)O(log n)O(log n)O(log n)

LRU cache with LinkedHashMap

  • Pass true as the third constructor argument to make LinkedHashMap access-ordered: every get or put moves that key to the end.
  • Override removeEldestEntry to drop the least recently used entry when the map grows past a limit.
  • Real life: the recent apps screen on a phone that keeps only the last few apps you used.
import java.util.LinkedHashMap;
import java.util.Map;

public class RecentApps {
    static class LruCache<K, V> extends LinkedHashMap<K, V> {
        private final int capacity;

        LruCache(int capacity) {
            super(16, 0.75f, true);                  // true = access order
            this.capacity = capacity;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > capacity;                // drop the least recently used
        }
    }

    public static void main(String[] args) {
        LruCache<String, String> recent = new LruCache<>(3);
        recent.put("WhatsApp", "chat");
        recent.put("Maps", "route");
        recent.put("Camera", "photo");
        recent.get("WhatsApp");                      // used again: moves to the end
        recent.put("YouTube", "video");              // full: Maps (least recent) is removed

        System.out.println(recent.keySet());         // [Camera, WhatsApp, YouTube]
    }
}

Thread-safe maps: ConcurrentHashMap

  • HashMap is not thread-safe. Concurrent put calls can lose updates, and counters end up wrong.
  • ConcurrentHashMap locks only a small part of the table during writes, and reads mostly need no lock — so many threads work in parallel.
  • Check-then-act (if (!map.containsKey(k)) map.put(k, v)) is not atomic even on ConcurrentHashMap. Use putIfAbsent, computeIfAbsent, or merge.
  • Real life: a cricket score website where four servers count page views for each live match at the same time.
OptionLockingnull keys/valuesUse when
HashMapNoneAllowedSingle thread only
HashtableWhole map, every methodNot allowedNever in new code
Collections.synchronizedMap(map)Whole mapSame as wrapped mapLow traffic; lock manually while iterating
ConcurrentHashMapPer bucket (fine-grained)Not allowedShared caches, counters, high traffic
ConcurrentSkipListMapLock-freeNot allowedConcurrent sorted map (concurrent TreeMap)
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class LiveScoreViews {
    public static void main(String[] args) throws InterruptedException {
        Map<String, Integer> views = new ConcurrentHashMap<>();
        String[] matches = { "IND-AUS", "ENG-SA", "IND-AUS", "NZ-PAK" };
        ExecutorService servers = Executors.newFixedThreadPool(4);   // 4 web servers

        for (int s = 0; s < 4; s++) {
            servers.submit(() -> {
                for (int i = 0; i < 10_000; i++) {
                    views.merge(matches[i % matches.length], 1, Integer::sum);   // atomic update
                }
            });
        }
        servers.shutdown();
        servers.awaitTermination(5, TimeUnit.SECONDS);

        System.out.println("IND-AUS: " + views.get("IND-AUS"));   // always 20000
        System.out.println("ENG-SA:  " + views.get("ENG-SA"));    // always 10000
        System.out.println("NZ-PAK:  " + views.get("NZ-PAK"));    // always 10000
    }
}

Immutable maps and EnumMap

  • Map.of(k1, v1, ...) (up to 10 pairs) and Map.ofEntries(Map.entry(k, v), ...) create immutable maps. They reject nulls and duplicate keys.
  • Map.copyOf(map) makes an immutable snapshot; Collections.unmodifiableMap(map) is only a read-only view that still reflects changes to the original.
  • EnumMap is the fastest map when keys are enum constants: it is backed by an array and iterates in enum order.
  • Real life: a fixed country-capital list for a quiz, and a traffic signal controller storing seconds for each light.
import java.util.EnumMap;
import java.util.Map;

public class TrafficSignal {
    enum Light { RED, YELLOW, GREEN }

    public static void main(String[] args) {
        Map<String, String> capitals = Map.of("India", "New Delhi", "Japan", "Tokyo");
        // capitals.put("France", "Paris");        // UnsupportedOperationException
        System.out.println(capitals.get("Japan"));  // Tokyo

        Map<Light, Integer> seconds = new EnumMap<>(Light.class);
        seconds.put(Light.GREEN, 45);
        seconds.put(Light.RED, 60);
        seconds.put(Light.YELLOW, 5);
        System.out.println(seconds);                // {RED=60, YELLOW=5, GREEN=45} (enum order)

        int cycle = 0;
        for (int s : seconds.values()) cycle += s;
        System.out.println("Full cycle: " + cycle + " seconds");   // 110
    }
}

Maps with streams

  • Collectors.groupingBy builds a map of groups, optionally with a downstream collector such as counting() or summingInt(...).
  • Collectors.toMap(key, value, merge) builds a map directly; the merge function decides what happens on duplicate keys (without it you get IllegalStateException).
  • Pass TreeMap::new as the map factory to get sorted output.
  • Real life: an electronics chain building a revenue report by city and a sales count by product.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class SalesReport {
    record Sale(String city, String product, int amount) { }

    public static void main(String[] args) {
        List<Sale> sales = List.of(
            new Sale("Hyderabad", "Laptop", 55000),
            new Sale("Pune", "Phone", 20000),
            new Sale("Hyderabad", "Phone", 18000),
            new Sale("Chennai", "Laptop", 60000),
            new Sale("Pune", "Laptop", 52000)
        );

        Map<String, Integer> revenueByCity = sales.stream()
            .collect(Collectors.groupingBy(Sale::city, TreeMap::new, Collectors.summingInt(Sale::amount)));
        System.out.println(revenueByCity);     // {Chennai=60000, Hyderabad=73000, Pune=72000}

        Map<String, Long> unitsByProduct = sales.stream()
            .collect(Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.counting()));
        System.out.println(unitsByProduct);    // {Laptop=3, Phone=2}

        Map<String, Integer> biggestSale = sales.stream()
            .collect(Collectors.toMap(Sale::city, Sale::amount, Math::max, TreeMap::new));
        System.out.println(biggestSale);       // {Chennai=60000, Hyderabad=55000, Pune=52000}

        String topCity = revenueByCity.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .get()
            .getKey();
        System.out.println("Top city: " + topCity);   // Top city: Hyderabad
    }
}

HashMap best practices

PracticeWhy
Declare as Map<K, V>, create as new HashMap<>()Easy to switch to LinkedHashMap or TreeMap later
Use immutable keys (String, Integer, records)Avoids the lost entry trap
Override equals and hashCode togetherKeys are found correctly
Iterate with entrySet() or forEachOne lookup per entry instead of two
Use merge, computeIfAbsent, getOrDefaultShorter code and fewer lookups
Pre-size when the count is knownSkips costly resizes
Guard against null when unboxing get resultsPrevents NullPointerException
Use ConcurrentHashMap for shared mapsHashMap corrupts data under threads
Pick LinkedHashMap for order, TreeMap for sortingHashMap order is never guaranteed
Never modify a map inside a for-each over itAvoids ConcurrentModificationException
L3

Tricky Interview Points

Q1) What is a HashMap?

Answer A Map implementation that stores unique keys mapped to values in a hash table. put, get, and remove are O(1) on average. It allows one null key and many null values and keeps no order.

Q2) How does HashMap work internally?

Answer It keeps an array of buckets. The key hashCode is spread (h ^ h >>> 16) and masked with (n - 1) to pick a bucket. Inside the bucket, equals finds the exact key. Collisions are stored as a linked list, or a red-black tree when a bucket grows beyond 8 nodes. The table doubles when size exceeds capacity × load factor.

Q3) Why must you override hashCode when you override equals?

Answer HashMap first uses hashCode to choose a bucket and only then calls equals. If two equal keys have different hash codes, they go to different buckets, so get returns null and duplicate keys can appear.

Q4) What happens when two keys have the same hashCode?

Answer That is a collision. Both entries live in the same bucket and are told apart by equals. Lookups stay correct but get slower if many keys collide.

Q5) What is the load factor and default capacity?

Answer Default capacity is 16 buckets and the default load factor is 0.75. When the number of entries exceeds 16 × 0.75 = 12, the table doubles to 32 and all entries are rehashed.

Q6) What is treeification in Java 8?

Answer When one bucket holds more than 8 nodes and the table has at least 64 buckets, the list is converted into a red-black tree. This improves worst-case lookup from O(n) to O(log n). It converts back to a list when it shrinks below 6.

Q7) Why is HashMap capacity always a power of 2?

Answer So the bucket index can be computed with a fast bitwise AND, (n - 1) & hash, instead of a slower modulo. It also makes resizing simple: each entry either stays in its index or moves by exactly the old capacity.

Q8) Can HashMap have a null key?

Answer Yes, exactly one. Its hash is treated as 0, so it always goes to bucket 0. Hashtable, ConcurrentHashMap, and TreeMap with natural ordering do not allow null keys.

Q9) What does put return?

Answer The previous value for that key, or null if the key was new (or was mapped to null).

Q10) What is the difference between HashMap and Hashtable?

Answer Hashtable is legacy and synchronized on every method, allows no null keys or values, and is slower. HashMap is not synchronized, allows one null key and null values, and is the modern choice. For threads, use ConcurrentHashMap instead of Hashtable.

Q11) What is the difference between HashMap and ConcurrentHashMap?

Answer HashMap is not thread-safe. ConcurrentHashMap allows many threads to read and write at once by locking only individual buckets, provides atomic methods like merge and computeIfAbsent, and does not allow null keys or values.

Q12) HashMap vs LinkedHashMap vs TreeMap?

Answer HashMap has no order and O(1) operations. LinkedHashMap keeps insertion (or access) order with O(1) operations. TreeMap keeps keys sorted with O(log n) operations and supports range queries like floorKey and subMap.

Q13) What happens if a key is modified after being put in a HashMap?

Answer If the change affects hashCode, the entry stays in its old bucket and can no longer be found with get or containsKey. It still counts in size, causing a memory leak. Keys should be immutable.

Q14) How do you iterate a HashMap efficiently?

Answer Use entrySet() or forEach((k, v) -> ...). Looping over keySet() and calling get(key) performs an extra lookup for every key.

Q15) How do you remove entries while iterating?

Answer Use Iterator.remove() on the entrySet iterator, or removeIf on entrySet(), keySet(), or values(). Calling map.remove inside a for-each loop throws ConcurrentModificationException.

Q16) What is the difference between getOrDefault and get?

Answer get returns null for a missing key. getOrDefault returns the given default for a missing key. If the key exists with a null value, both return null.

Q17) Explain putIfAbsent, computeIfAbsent, and merge.

Answer putIfAbsent adds a value only if the key is missing. computeIfAbsent creates the value lazily with a function if missing and returns it, ideal for grouping. merge adds a value if absent or combines it with the existing value, ideal for counting.

Q18) How do you build an LRU cache in Java?

Answer Extend LinkedHashMap with accessOrder set to true in the constructor and override removeEldestEntry to return true when size() exceeds the capacity. Every get moves a key to the end, and the oldest entry is removed automatically.

Q19) What is the time complexity of HashMap operations?

Answer put, get, remove, and containsKey are O(1) on average. containsValue is O(n). Worst case lookup is O(log n) since Java 8 because of tree bins (O(n) before Java 8).

Q20) Is HashMap ordered? Can the order change?

Answer No order is guaranteed. The order depends on hash codes and table size, and it can change after a resize. Use LinkedHashMap for insertion order or TreeMap for sorted order.

L4

Simple Programs

Top words in customer reviews

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReviewWords {
    public static void main(String[] args) {
        String reviews = "Great phone. Battery is great, camera is great. Battery lasts long. Camera is sharp.";

        Map<String, Integer> freq = new HashMap<>();
        for (String w : reviews.toLowerCase().split("[^a-z]+")) {
            if (w.length() > 2) freq.merge(w, 1, Integer::sum);   // skip tiny words like "is"
        }

        List<Map.Entry<String, Integer>> list = new ArrayList<>(freq.entrySet());
        list.sort(Map.Entry.<String, Integer>comparingByValue().reversed()
                .thenComparing(Map.Entry.comparingByKey()));

        System.out.println("Top 3 words:");
        for (int i = 0; i < 3 && i < list.size(); i++) {
            System.out.println(list.get(i).getKey() + " = " + list.get(i).getValue());
        }
        // great = 3
        // battery = 2
        // camera = 2
    }
}

Match two invoices to a payment (Two Sum)

import java.util.HashMap;
import java.util.Map;

public class InvoiceMatch {
    static int[] findPair(int[] invoices, int payment) {
        Map<Integer, Integer> seen = new HashMap<>();          // amount -> invoice index
        for (int i = 0; i < invoices.length; i++) {
            Integer j = seen.get(payment - invoices[i]);       // the partner amount seen earlier?
            if (j != null) return new int[] { j, i };
            seen.put(invoices[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] invoices = { 1200, 4500, 800, 3000, 2700 };
        int payment = 3500;
        int[] pair = findPair(invoices, payment);
        if (pair == null) {
            System.out.println("No two invoices add up to " + payment);
        } else {
            System.out.println("Invoices #" + pair[0] + " and #" + pair[1] + ": "
                + invoices[pair[0]] + " + " + invoices[pair[1]] + " = " + payment);
        }
        // Invoices #2 and #4: 800 + 2700 = 3500   (one pass, O(n))
    }
}

Kirana store inventory with low-stock alerts

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Inventory {
    private final Map<String, Integer> stock = new HashMap<>();    // item -> quantity

    void receive(String item, int qty) {
        stock.merge(item, qty, Integer::sum);
    }

    boolean sell(String item, int qty) {
        int have = stock.getOrDefault(item, 0);
        if (have < qty) {
            System.out.println("Cannot sell " + qty + " " + item + " (only " + have + " left)");
            return false;
        }
        stock.put(item, have - qty);
        return true;
    }

    void lowStockReport(int limit) {
        new TreeMap<>(stock).forEach((item, qty) -> {               // sorted copy for a neat report
            if (qty < limit) System.out.println("Reorder " + item + " (" + qty + " left)");
        });
    }

    public static void main(String[] args) {
        Inventory shop = new Inventory();
        shop.receive("Rice", 50);
        shop.receive("Sugar", 20);
        shop.receive("Oil", 10);
        shop.receive("Rice", 25);                  // Rice now 75
        shop.sell("Sugar", 15);                    // Sugar 5
        shop.sell("Oil", 12);                      // Cannot sell 12 Oil (only 10 left)
        shop.sell("Oil", 4);                       // Oil 6
        shop.sell("Ghee", 1);                      // Cannot sell 1 Ghee (only 0 left)

        System.out.println(new TreeMap<>(shop.stock));   // {Oil=6, Rice=75, Sugar=5}
        shop.lowStockReport(8);
        // Reorder Oil (6 left)
        // Reorder Sugar (5 left)
    }
}

Group anagrams for a word puzzle game

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class AnagramGroups {
    public static void main(String[] args) {
        String[] words = { "listen", "silent", "enlist", "google", "inlets", "banana", "gogole" };

        Map<String, List<String>> groups = new LinkedHashMap<>();    // sorted letters -> words
        for (String w : words) {
            char[] letters = w.toCharArray();
            Arrays.sort(letters);
            groups.computeIfAbsent(new String(letters), k -> new ArrayList<>()).add(w);
        }

        groups.values().forEach(System.out::println);
        // [listen, silent, enlist, inlets]
        // [google, gogole]
        // [banana]
    }
}

Longest stretch of unique songs in a playlist

import java.util.HashMap;
import java.util.Map;

public class UniquePlaylist {
    static int longestUnique(String[] songs) {
        Map<String, Integer> lastSeen = new HashMap<>();     // song -> last position played
        int best = 0;
        int start = 0;
        for (int i = 0; i < songs.length; i++) {
            Integer prev = lastSeen.get(songs[i]);
            if (prev != null && prev >= start) {
                start = prev + 1;                            // repeat inside window: move the start
            }
            lastSeen.put(songs[i], i);
            best = Math.max(best, i - start + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        String[] played = { "Kesariya", "Naatu", "Jhoome", "Naatu", "Srivalli", "Apna", "Kesariya", "Jhoome" };
        System.out.println("Longest stretch of unique songs: " + longestUnique(played));
        // 5 (Jhoome, Naatu, Srivalli, Apna, Kesariya)
    }
}

First one-time visitor and first unique character

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstUnique {
    static String firstOneTime(String[] log) {
        Map<String, Integer> visits = new LinkedHashMap<>();   // keeps first-visit order
        for (String v : log) visits.merge(v, 1, Integer::sum);
        for (Map.Entry<String, Integer> e : visits.entrySet()) {
            if (e.getValue() == 1) return e.getKey();
        }
        return "none";
    }

    static char firstUniqueChar(String s) {
        Map<Character, Integer> count = new LinkedHashMap<>();
        for (char c : s.toCharArray()) count.merge(c, 1, Integer::sum);
        for (Map.Entry<Character, Integer> e : count.entrySet()) {
            if (e.getValue() == 1) return e.getKey();
        }
        return '-';
    }

    public static void main(String[] args) {
        String[] gateLog = { "Ravi", "Asha", "Ravi", "Kiran", "Asha", "Meena", "Kiran" };
        System.out.println("First one-time visitor: " + firstOneTime(gateLog));   // Meena
        System.out.println("First unique char in swiss: " + firstUniqueChar("swiss"));   // w
    }
}

Mini bank with accounts and transfers

import java.util.HashMap;
import java.util.Map;

public class MiniBank {
    private final Map<String, Long> balances = new HashMap<>();   // account number -> balance

    void open(String account, long amount) {
        if (balances.putIfAbsent(account, amount) != null) {
            System.out.println("Account " + account + " already exists");
        }
    }

    boolean transfer(String from, String to, long amount) {
        Long fromBalance = balances.get(from);
        if (fromBalance == null || !balances.containsKey(to)) {
            System.out.println("Invalid account");
            return false;
        }
        if (fromBalance < amount) {
            System.out.println("Insufficient balance in " + from);
            return false;
        }
        balances.put(from, fromBalance - amount);
        balances.merge(to, amount, Long::sum);
        return true;
    }

    public static void main(String[] args) {
        MiniBank bank = new MiniBank();
        bank.open("SB1001", 5000);
        bank.open("SB1002", 1200);
        bank.open("SB1001", 9999);                   // Account SB1001 already exists

        bank.transfer("SB1001", "SB1002", 1500);     // success
        bank.transfer("SB1002", "SB1001", 9000);     // Insufficient balance in SB1002
        bank.transfer("SB1001", "SB9999", 100);      // Invalid account

        System.out.println("SB1001: " + bank.balances.get("SB1001"));   // 3500
        System.out.println("SB1002: " + bank.balances.get("SB1002"));   // 2700
    }
}
L5

Problem Solving Tricks

  • Need to look something up by a name, ID, or code? Think Map. Need it fast? Think HashMap.
  • Count anything with map.merge(key, 1, Integer::sum).
  • Group anything with map.computeIfAbsent(key, k -> new ArrayList<>()).add(item).
  • HashMap = no order, LinkedHashMap = insertion order, TreeMap = sorted keys.
  • Loop with entrySet(), not keySet() plus get().
  • Use records or immutable classes as keys, and never change a key while it is in the map.
  • put returns the old value — use it to detect "new key or update?" in one call.
  • Unbox carefully: int x = map.get(k) throws NPE when the key is missing; use getOrDefault.
  • LRU cache in 10 lines: LinkedHashMap with access order plus removeEldestEntry.
  • Shared between threads? Use ConcurrentHashMap and its atomic merge / computeIfAbsent.
L6

Practice Programs List

  1. Build a phone book that adds, updates, searches, and deletes contacts by name.
  2. Count how many times each word appears in a paragraph and print the top 3.
  3. Count votes for candidates and announce the winner, handling a tie.
  4. Build a shopping cart with add, increase, decrease, and remove using merge and computeIfPresent.
  5. Group a list of students by city using computeIfAbsent.
  6. Find the first non-repeating character in a string using LinkedHashMap.
  7. Solve Two Sum with a HashMap in one pass and explain why it is O(n).
  8. Create a Seat record as a key and show that a new Seat object finds the booking.
  9. Write a key class with only equals, show get failing, then fix it with hashCode.
  10. Show the lost entry problem by changing a key field after put.
  11. Print the same entries from HashMap, LinkedHashMap, and TreeMap and explain the order.
  12. Use TreeMap.floorEntry to convert marks into grades.
  13. Build an LRU cache of size 3 for recently opened files using LinkedHashMap.
  14. Count page views from 4 threads with ConcurrentHashMap.merge and compare with a plain HashMap.