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.

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:

To visit every pair, loop over entrySet() and read each entry's key and value. To visit only keys, loop over keySet() .

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 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 .

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.

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.