Learn Java
import com.learnjava.datastructurescollections.HashmapTreemap;

HashMap & TreeMap in Java

@Concept

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.

@HowItWorks
1

Key-value pairs

A Map associates each unique key with exactly one value, retrieved later by that same key.

2

HashMap

No guaranteed order, but constant-time get, put, and remove on average.

3

TreeMap

Keeps keys sorted at all times, using their natural ordering or a supplied Comparator, at logarithmic-time cost per operation.

4

Keys are unique

put(key, value) on a key that already exists overwrites its previous value rather than creating a second entry.

5

getOrDefault avoids null checks

map.getOrDefault(key, fallback) returns fallback directly when the key isn't present, instead of returning null.

@Example
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));
}
}
Output
Ana's age: 31
Unknown: 0
1Putting "Ana" a second time with a new value overwrites the first, rather than creating a duplicate entry.
2ages.get("Ana") retrieves that final, overwritten value, 31.
3"Cy" was never added to the map at all, so getOrDefault returns the supplied fallback, 0, instead of null.
4Both println calls run once each, giving two lines of output.
@Complexity
time HashMap: O(1) average for get/put/remove; TreeMap: O(log n) for the same operations
space O(n)

The same trade-off as HashSet versus TreeSet applies here, just for key-value pairs instead of standalone elements.

@UseCases
Looking up a value by a meaningful key instead of a numeric index, like a username to a user record
Counting occurrences of items by using each item as a key and a running count as its value
Avoiding null-handling boilerplate with getOrDefault when a key might not be present
Keeping keys sorted automatically, like an alphabetized lookup table, with TreeMap

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.