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.
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 aMapimplementation injava.utilthat 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, andremovetake 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 scenario | Key | Value | Why a HashMap |
|---|---|---|---|
| Phone contacts | Name | Phone number | Instant lookup by name |
| Dictionary app | Word | Meaning | Find any word in O(1) |
| Shopping cart | Product ID | Quantity | Update quantity of one product quickly |
| Bank system | Account number | Balance | Fetch and update a balance directly |
| Railway reservation | PNR number | Booking details | Check status with one key |
| RTO vehicle registry | Vehicle number | Owner details | Trace the owner of a number plate |
| Election counting | Candidate | Vote count | Increment the right counter for every vote |
| Student report | Roll number | Marks | Teacher looks up marks by roll number |
| Browser cache | URL | Saved page | Serve a page without downloading again |
| Login system | Session token | Logged-in user | Identify the user on every request |
| Country quiz | Country | Capital | Check an answer instantly |
| Restaurant menu | Dish | Price | Calculate the bill item by item |
Features of HashMap
| Feature | Meaning |
|---|---|
| Key-value pairs | Every entry is a key mapped to a value |
| Unique keys | Same key again replaces the value (decided by equals and hashCode) |
| Duplicate values | Allowed: two students can have the same marks |
| null | One null key and any number of null values |
| No order | Iteration order is unpredictable and can change after resizing |
| Speed | Average O(1) for put, get, remove, containsKey |
| Defaults | Capacity 16, load factor 0.75 |
| Thread-safe | No (use ConcurrentHashMap for threads) |
| Iterator | Fail-fast: modifying the map while looping throws ConcurrentModificationException |
| Interfaces | Map, Cloneable, Serializable (not Collection) |
Creating a HashMap
| Constructor or factory | Meaning |
|---|---|
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
| Method | What it does | Real-life use |
|---|---|---|
put(k, v) | Adds or replaces; returns the old value or null | Save a contact number |
putAll(m) | Copies all entries from another map | Merge two price lists |
get(k) | Value for the key, or null if absent | Look up a PNR booking |
getOrDefault(k, d) | Value, or the default if the key is absent | Price of a dish, 0 if not on the menu |
containsKey(k) | True if the key exists | Is 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 value | Delete a contact |
remove(k, v) | Removes only if the key maps to that value | Cancel a seat only if it is still yours |
replace(k, v) | Replaces only if the key exists | Update stock of an existing product |
putIfAbsent(k, v) | Adds only if the key is missing | Register a username only once |
computeIfAbsent(k, f) | Creates the value with f if missing, returns it | Create a department list on first employee |
computeIfPresent(k, f) | Recomputes the value only if present | Apply a discount to an existing item |
compute(k, f) | Recomputes the value whether present or not | Update a running score |
merge(k, v, f) | Puts v if absent, else combines old and v with f | Count votes per candidate |
keySet() | View of all keys | List of all registered usernames |
values() | View of all values | Sum of all account balances |
entrySet() | View of all key-value pairs | Print a report card |
forEach(f) | Runs f for each key and value | Send a reminder to every member |
replaceAll(f) | Replaces every value using f | Add 18% GST to every price |
size() / isEmpty() | Number of entries / true if none | Items in cart / is the cart empty? |
clear() | Removes all entries | Empty the cart after checkout |
Adding, updating, and removing entries
putreturns the previous value (ornull), so you can tell whether it was an add or an update.putIfAbsentadds only new keys,replacechanges only existing keys, andmergeadds 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
getreturnsnullfor a missing key — and also for a key whose value isnull. UsecontainsKeywhen you must tell them apart.getOrDefaultgives a fallback only when the key is absent, not when the stored value isnull.- Unboxing trap:
int price = map.get("Juice");throwsNullPointerExceptionwhen 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. UseentrySet()instead. - Never call
map.removeinside a for-each loop; it throwsConcurrentModificationException. UseIterator.removeorremoveIf. - Real life: a class teacher printing a report card, finding the average, and removing failed students from a toppers list.
| Way | Gives you | Best for |
|---|---|---|
entrySet() loop | Key and value together | Most loops (fastest, one lookup) |
keySet() loop | Only keys | When values are not needed |
values() loop | Only values | Totals and averages |
forEach((k, v) -> ...) | Key and value | Short, readable code |
Iterator on entrySet() | Key and value with remove() | Removing while looping |
removeIf on a view | Condition-based removal | One-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), andcompute(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 andputan empty list, thenget(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
hashCodeto find the bucket andequalsto match the key. Both must be overridden using the same fields. - A
recordgenerates correctequalsandhashCodeautomatically 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
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Order of keys | No order | Insertion order (or access order) | Sorted by key |
| Internal structure | Hash table | Hash table + doubly linked list | Red-black tree |
| put / get / remove | O(1) average | O(1) average | O(log n) |
| null key | One allowed | One allowed | Not allowed (natural ordering) |
| null values | Allowed | Allowed | Allowed |
| Key requirement | equals + hashCode | equals + hashCode | Comparable or a Comparator |
| Memory | Lowest | More (links) | More (tree nodes) |
| Extra features | None | LRU cache via access order | floorKey, ceilingKey, subMap, headMap |
| Real-life use | Phone contacts | Restaurant order queue | Train 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
LinkedHashMapis 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(), andpollFirstEntry()becauseLinkedHashMapis aSequencedMap. - 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
TreeMapkeeps keys sorted (natural order or aComparator) and answers "nearest key" questions that HashMap cannot.- Operations take O(log n). Keys must be comparable, and a
nullkey is not allowed. - Real life: converting marks to a grade with
floorEntry, and finding the next train after a given time withceilingEntry.
| Method | Returns | Train timetable example |
|---|---|---|
firstKey() / lastKey() | Smallest / largest key | First and last train of the day |
floorKey(k) | Largest key ≤ k | Last train at or before 10:00 |
ceilingKey(k) | Smallest key ≥ k | Next train at or after 10:00 |
lowerKey(k) / higherKey(k) | Strictly < k / strictly > k | Train just before / just after a time |
headMap(k) | Keys < k | All morning trains (before 12:00) |
tailMap(k) | Keys ≥ k | All 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 entry | Remove a train once it departs |
descendingMap() | Reverse-ordered view | Timetable 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
| Feature | HashMap | Hashtable |
|---|---|---|
| Introduced | Java 1.2 (Collections Framework) | Java 1.0 (legacy) |
| Thread-safe | No | Yes (every method synchronized) |
| Speed | Fast | Slower due to locking |
| null key / values | One null key, many null values | Neither allowed (NullPointerException) |
| Iteration | Fail-fast Iterator | Enumeration (not fail-fast) and Iterator |
| Parent class | AbstractMap | Dictionary |
| Default capacity | 16 | 11 |
| Modern replacement | — | ConcurrentHashMap for threads |
| Use today | Yes, everywhere | No, only in old code |
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, andnext. - 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.
| Step | What put(key, value) does | Cloak room analogy |
|---|---|---|
| 1 | Calls key.hashCode() | Read the token number |
| 2 | Spreads the bits: h ^ (h >>> 16) | Mix the digits so racks fill evenly |
| 3 | Bucket index = (n - 1) & hash (n = table size) | Work out the rack number |
| 4 | Empty bucket: store a new node there | Empty rack: keep the bag |
| 5 | Otherwise walk the bucket; if equals matches, replace the value and return the old one | Same token found: swap the bag |
| 6 | No match: append a node (list) or insert into a tree bin | Different token: add the bag to the rack |
| 7 | Increase size; resize if size > capacity × load factor | Racks 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) ornew 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 added | Capacity | Threshold (× 0.75) | What happens |
|---|---|---|---|
| 0 to 12 | 16 | 12 | No resize |
| 13th entry | 16 → 32 | 24 | First resize: all entries rehashed |
| 25th entry | 32 → 64 | 48 | Second resize |
| 49th entry | 64 → 128 | 96 | Third resize |
| 97th entry | 128 → 256 | 192 | Fourth resize |
| Pre-sized for 100 | 256 from the start | 192 | Zero 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
equalsto 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(likeStringandInteger). - 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.
| Constant | Value | Meaning |
|---|---|---|
TREEIFY_THRESHOLD | 8 | A bucket list longer than this becomes a tree |
UNTREEIFY_THRESHOLD | 6 | A tree smaller than this (after resize) becomes a list again |
MIN_TREEIFY_CAPACITY | 64 | Below this table size, HashMap resizes instead of treeifying |
| Worst case before Java 8 | O(n) | All keys in one long list |
| Worst case since Java 8 | O(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.
| Rule | What goes wrong if broken |
|---|---|
| Equal objects must have equal hash codes | get searches the wrong bucket and returns null |
Override equals and hashCode together | Duplicate keys appear; lookups fail |
| Use the same fields in both methods | Keys that are equal end up in different buckets |
| Unequal objects may share a hash code | Allowed (a collision), but too many slow the map down |
| hashCode must not change while the key is in the map | The 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
| Operation | HashMap | LinkedHashMap | TreeMap | ConcurrentHashMap |
|---|---|---|---|---|
put | O(1) avg | O(1) avg | O(log n) | O(1) avg |
get / containsKey | O(1) avg | O(1) avg | O(log n) | O(1) avg |
remove | O(1) avg | O(1) avg | O(log n) | O(1) avg |
containsValue | O(n) | O(n) | O(n) | O(n) |
| Iterate all entries | O(capacity + n) | O(n) | O(n) | O(capacity + n) |
| First / last key | Not supported | O(1) (Java 21) | O(log n) | Not supported |
| Worst case lookup | O(log n) (tree bins) | O(log n) | O(log n) | O(log n) |
LRU cache with LinkedHashMap
- Pass
trueas the third constructor argument to makeLinkedHashMapaccess-ordered: everygetorputmoves that key to the end. - Override
removeEldestEntryto 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
HashMapis not thread-safe. Concurrentputcalls can lose updates, and counters end up wrong.ConcurrentHashMaplocks 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 onConcurrentHashMap. UseputIfAbsent,computeIfAbsent, ormerge. - Real life: a cricket score website where four servers count page views for each live match at the same time.
| Option | Locking | null keys/values | Use when |
|---|---|---|---|
HashMap | None | Allowed | Single thread only |
Hashtable | Whole map, every method | Not allowed | Never in new code |
Collections.synchronizedMap(map) | Whole map | Same as wrapped map | Low traffic; lock manually while iterating |
ConcurrentHashMap | Per bucket (fine-grained) | Not allowed | Shared caches, counters, high traffic |
ConcurrentSkipListMap | Lock-free | Not allowed | Concurrent 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) andMap.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.EnumMapis 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.groupingBybuilds a map of groups, optionally with a downstream collector such ascounting()orsummingInt(...).Collectors.toMap(key, value, merge)builds a map directly; the merge function decides what happens on duplicate keys (without it you getIllegalStateException).- Pass
TreeMap::newas 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
| Practice | Why |
|---|---|
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 together | Keys are found correctly |
Iterate with entrySet() or forEach | One lookup per entry instead of two |
Use merge, computeIfAbsent, getOrDefault | Shorter code and fewer lookups |
| Pre-size when the count is known | Skips costly resizes |
Guard against null when unboxing get results | Prevents NullPointerException |
Use ConcurrentHashMap for shared maps | HashMap corrupts data under threads |
| Pick LinkedHashMap for order, TreeMap for sorting | HashMap order is never guaranteed |
| Never modify a map inside a for-each over it | Avoids ConcurrentModificationException |
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.
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
}
} 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(), notkeySet()plusget(). - Use records or immutable classes as keys, and never change a key while it is in the map.
putreturns 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; usegetOrDefault. - LRU cache in 10 lines:
LinkedHashMapwith access order plusremoveEldestEntry. - Shared between threads? Use
ConcurrentHashMapand its atomicmerge/computeIfAbsent.
Practice Programs List
- Build a phone book that adds, updates, searches, and deletes contacts by name.
- Count how many times each word appears in a paragraph and print the top 3.
- Count votes for candidates and announce the winner, handling a tie.
- Build a shopping cart with add, increase, decrease, and remove using
mergeandcomputeIfPresent. - Group a list of students by city using
computeIfAbsent. - Find the first non-repeating character in a string using
LinkedHashMap. - Solve Two Sum with a HashMap in one pass and explain why it is O(n).
- Create a
Seatrecord as a key and show that a newSeatobject finds the booking. - Write a key class with only
equals, showgetfailing, then fix it withhashCode. - Show the lost entry problem by changing a key field after
put. - Print the same entries from HashMap, LinkedHashMap, and TreeMap and explain the order.
- Use
TreeMap.floorEntryto convert marks into grades. - Build an LRU cache of size 3 for recently opened files using
LinkedHashMap. - Count page views from 4 threads with
ConcurrentHashMap.mergeand compare with a plain HashMap.