HashMap & TreeMap in Java
HashMap and TreeMap, from java.util, both store key-value pairs, retrieving a value by its associated key rather than by position. HashMap offers no guaranteed order but constant-time get, put, and remove on average; TreeMap keeps its keys sorted at all times, at logarithmic-time cost instead.
A Map's keys are themselves unique, just like a Set's elements — putting a value at a key that already exists overwrites the previous value rather than adding a second entry. Both map types also offer a getOrDefault method that returns a fallback value instead of null when a key isn't present, avoiding an extra explicit containsKey check.
Key-value pairs
A Map associates each unique key with exactly one value, retrieved later by that same key.
HashMap
No guaranteed order, but constant-time get, put, and remove on average.
TreeMap
Keeps keys sorted at all times, using their natural ordering or a supplied Comparator, at logarithmic-time cost per operation.
Keys are unique
put(key, value) on a key that already exists overwrites its previous value rather than creating a second entry.
getOrDefault avoids null checks
map.getOrDefault(key, fallback) returns fallback directly when the key isn't present, instead of returning null.
import java.util.HashMap; public class MapDemo { public static void main(String[] args) { HashMap<String, Integer> ages = new HashMap<>(); ages.put("Ana", 30); ages.put("Bo", 25); ages.put("Ana", 31); System.out.println("Ana's age: " + ages.get("Ana")); System.out.println("Unknown: " + ages.getOrDefault("Cy", 0)); }}The same trade-off as HashSet versus TreeSet applies here, just for key-value pairs instead of standalone elements.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.