← Back to Week 3 Hub

HashMap Operations & Iteration

Add, look up, remove, and loop through key/value pairs. Every method operates on the key — that's the whole point of a map.

Every operation uses the key. put(key, value), get(key), remove(key), containsKey(key). If you want to loop through all entries, use values(), keySet(), or entrySet() — three different views of the same map.
HashMap<String, String> statesAndCapitals
size(): 0
put(key, value) — add or update
get(key) — returns value or null
remove(key)
bulk

Iterating through a HashMap — three ways

Click a button to see what that iteration style produces.
Watch out: get("OK") on a map without an "OK" key returns nullnot an error. If you try to use the returned value immediately, you'll hit a NullPointerException.
String value = map.get("OK"); if (value != null) { // safe to use value here System.out.println(value); } else { System.out.println("not in the map"); }
Call log

Tip: the list you see above won't always match insertion order — HashMaps use bucket order. If order matters, use a LinkedHashMap or a List instead.

← HashMap Hashing & Buckets ArrayList vs HashMap →