HashMap: Key-Value Lookup

Introduction

HashMap stores key-value pairs with fast lookup by key—ideal for dictionaries, caches, and indexes (name → score). This chapter covers creation, CRUD, traversal, and generics: HashMap<String, Integer>.

Prerequisites

What Is a Map

java
import java.util.HashMap;
import java.util.Map;
 
Map<String, Integer> scores = new HashMap<>();
scores.put("Emma", 95);
scores.put("Liam", 88);
 
System.out.println(scores.get("Emma"));  // 95

Keys are unique—put with existing key replaces value.

1) Core Operations

java
Map<String, Integer> map = new HashMap<>();
 
map.put("Ava", 90);
map.put("Noah", 92);
 
int score = map.get("Ava");
Integer missing = map.get("Unknown");  // null if absent
 
map.putIfAbsent("Ava", 100);  // keeps 90
map.replace("Noah", 94);
 
boolean removed = map.remove("Ava");
map.clear();

2) Safe Lookup

java
int safe = map.getOrDefault("Unknown", 0);
 
Integer value = map.get("Emma");
if (value != null) {
    System.out.println(value);
}

Java 8+:

java
map.computeIfAbsent("NewStudent", name -> 0);

3) Check Keys and Values

java
boolean hasKey = map.containsKey("Emma");
boolean hasValue = map.containsValue(95);
int size = map.size();
boolean empty = map.isEmpty();

4) Traverse a Map

java
for (String key : map.keySet()) {
    System.out.println(key + " -> " + map.get(key));
}
 
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}
 
map.forEach((name, score) -> System.out.println(name + ": " + score));

Prefer entrySet() when you need both key and value—avoids double lookup.

5) Keys and hashCode

HashMap locates buckets using key hashCode() and equals().
Use immutable, well-defined keys (String, Integer, records). Mutable keys that change break lookup.

6) HashMap vs TreeMap (Awareness)

HashMapTreeMap
Orderno guaranteed ordersorted by keys
PerformanceO(1) average getO(log n)
Null keysone null key allowedno null keys (generally)

Real Mini Example: Word Count

java
import java.util.HashMap;
import java.util.Map;
 
public class WordCount {
    public static void main(String[] args) {
        String text = "java map map hash";
        Map<String, Integer> counts = new HashMap<>();
 
        for (String word : text.split(" ")) {
            counts.put(word, counts.getOrDefault(word, 0) + 1);
        }
 
        counts.forEach((word, count) ->
                System.out.println(word + ": " + count));
    }
}

Common Beginner Mistakes

Assuming get Returns 0 for Missing Key

Returns null for objects—use getOrDefault or null check.
Map.get on Map<String, int> does not exist—use Integer.

Using Mutable List as Key

Don't use ArrayList as key unless identity is intentional.

Iterating keySet and Calling remove on Map

Use iterator remove or map.remove(key) carefully—ConcurrentModificationException if concurrent structural change during enhanced-for.

Mini Practice

Build Map<String, String> phone book: add three entries, query one name.

What’s Next

Project: Score Entry and Query.

FAQ

Can keys and values be null?

HashMap allows one null key and multiple null values. Avoid unless intentional.

Is iteration order guaranteed?

No. Use LinkedHashMap for insertion order, TreeMap for sorted keys.

How is HashMap different from Hashtable?

Hashtable is legacy synchronized class; prefer HashMap or concurrent maps.

Primitive keys?

Use Integer, or specialized maps (advanced).

Thread safety?

Not thread-safe. Use ConcurrentHashMap in concurrent apps.