HashMap
An ArrayList finds items by position. But what if you want to find a person's phone number by their name ? A HashMap stores key→value pairs and looks any value up by its key, instantly — like a real dictionary or phone book.
Learn HashMap in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1️⃣ Keys and Values
A HashMap holds pairs. Each pair has a key (what you look up by) and a value (what you get back). Keys are unique; values can repeat.
💡 Analogy: A real dictionary maps a word (key) to its definition (value). You don't scan every page — you jump straight to the word. A HashMap does the same: get("Alice") goes directly to Alice's entry without checking everyone else.
You declare two types in the angle brackets — the key type and the value type. Both must be objects, so use wrapper classes for primitives:
2️⃣ The Core Methods
Method
What it does
put(k, v)
Add the pair, or overwrite if k exists
get(k)
Value for k, or null if absent
getOrDefault(k, d)
Value for k, or d if absent
containsKey(k)
Is there an entry for key k?
containsValue(v)
Does any entry hold value v?
remove(k)
Delete the entry for k
size()
Number of pairs
keySet()
All keys (for looping)
entrySet()
All key/value pairs (for looping)
3️⃣ Looping Over a HashMap
To visit every pair, loop over entrySet() and read each entry's key and value. To visit only keys, loop over keySet() .
4️⃣ The Tally Pattern (Counting Things)
The single most common HashMap pattern is counting occurrences : words in a sentence, votes per candidate, clicks per page. The trick is getOrDefault :
The first time a key is seen, getOrDefault returns the default 0 , so the count becomes 1. Every later time, it returns the existing count and adds one. Clean and bug-free, with no separate "is this the first time?" check.
🧩 Reorder Challenge
Reorder these lines to store one age and look it up.
Why: The map must exist before you put into it, and the pair must be stored before get can retrieve it. If you reversed put and get , the lookup would print null . Output: 28 .
🧠 Quick Recall
1 . Keys are unique, so the second put("a", 5) overwrites the value rather than adding a new entry.
-1 . The key "x" is absent, so getOrDefault returns the supplied default instead of null .
2 . First put: 0 + 1 = 1. Second put: 1 + 1 = 2. That's the tally pattern running twice.
Common Beginner Mistakes
- ❌ Calling a method on a null get(): map.get("missing").length() crashes. Use getOrDefault or containsKey .
- ❌ Primitive type arguments: HashMap<String, int> is illegal — use HashMap<String, Integer> .
- ❌ Expecting an order: HashMap iteration order is unpredictable. Use LinkedHashMap or TreeMap if order matters.
- ❌ Forgetting Map import: using Map.Entry needs import java.util.Map; .
- ❌ Duplicate keys "lost": putting the same key twice overwrites — it doesn't keep both.
📋 Quick Reference
Description
Example
new HashMap<>()
Create an empty map
HashMap<String, Integer> m = new HashMap<>();
Add pair, or overwrite if k exists
m.put("a", 1)
m.get("a")
m.getOrDefault("z", 0)
m.containsKey("a")
m.containsValue(1)
m.remove("a")
Number of key-value pairs
m.size()
for (String k : m.keySet())
values()
All values (for looping)
m.values()
All key-value pairs
for (Map.Entry<K,V> e : m.entrySet())
e.getKey() / e.getValue()
Read a pair while iterating
e.getKey()
getOrDefault(k,0)+1
Tally / count pattern
m.put(w, m.getOrDefault(w,0)+1)
merge(k, 1, Integer::sum)
Alternative tally one-liner
m.merge(w, 1, Integer::sum)
Frequently Asked Questions
🎉 Lesson Complete!
You now command Java's most useful collection for lookups: put and get pairs, dodge null with getOrDefault , check membership with containsKey , iterate with entrySet / keySet , and count things with the tally pattern.
Next up: a Checkpoint that combines data types, casting, Scanner, Math, StringBuilder, ArrayList and HashMap into one hands-on build.
Practice quiz
What does a HashMap store?
- Only values, by index
- Key-value pairs
- Unique values only
- Sorted numbers
Answer: Key-value pairs. A HashMap stores key-value pairs and looks values up by key.
What happens when you put the same key twice?
- It adds a second entry
- It overwrites the old value
- It throws an exception
- It ignores the new value
Answer: It overwrites the old value. Keys are unique; a second put with the same key overwrites the value.
After m.put('a',1); m.put('a',5); what is m.size()?
- 0
- 1
- 2
- 5
Answer: 1. Both puts use key 'a', so there is just one entry — size is 1.
What does get(key) return for a key that is not present?
- 0
- An empty string
- null
- It throws
Answer: null. get returns null for a missing key, which can cause a NullPointerException if used carelessly.
Which method returns a fallback instead of null for a missing key?
- get
- getOrDefault
- containsKey
- orElse
Answer: getOrDefault. getOrDefault(key, fallback) returns the fallback when the key is absent.
Which key type is illegal for a HashMap?
- String
- Integer
- int
- Character
Answer: int. Keys must be objects; use the wrapper Integer, not the primitive int.
How do you loop over every key-value pair?
- for (x : map)
- for (Map.Entry<K,V> e : map.entrySet())
- for (i = 0; i < map.size; i++)
- map.forEachKey()
Answer: for (Map.Entry<K,V> e : map.entrySet()). Iterate map.entrySet() and read e.getKey()/e.getValue().
Is a HashMap's iteration order guaranteed?
- Yes, insertion order
- Yes, sorted order
- No, it can look random
- Yes, reverse order
Answer: No, it can look random. HashMap order is not guaranteed; use LinkedHashMap for insertion order or TreeMap for sorted.
Which line correctly implements the word-count tally pattern?
- counts.add(word)
- counts.put(word, counts.getOrDefault(word, 0) + 1)
- counts.increment(word)
- counts.put(word, counts.get(word) + 1)
Answer: counts.put(word, counts.getOrDefault(word, 0) + 1). getOrDefault(word, 0) + 1 handles the first-time case cleanly without a null check.
Which class keeps keys in sorted order?
- HashMap
- LinkedHashMap
- TreeMap
- ArrayMap
Answer: TreeMap. TreeMap stores keys in sorted order.
Continue this course
- Previous: ArrayList
- Next: Checkpoint: Java Basics