Skip to content
Guest
Learn Java · Course Syllabus Show lessons
Modern Java APIs · 8 min read · Beginner

HashMap, HashSet & Frequency Maps

Use Map.getOrDefault(), Map.merge(), and Set deduplication for fast O(1) lookups in Java.

What you'll learn

  • Read Map values safely with getOrDefault()
  • Count occurrences cleanly in one line using map.merge(key, 1, Integer::sum)
  • Deduplicate collections with Set.copyOf() or HashSet

HashMap<K, V> and HashSet<T> provide average $O(1)$ lookups. Modern Java adds convenience methods like getOrDefault(key, 0) and merge(key, 1, Integer::sum) that replace verbose if (map.containsKey(...)) blocks.

Fill-in-the-Blank Exercise

Count Words with Map.merge

Increment the frequency count for each word cleanly with merge().

var counts = new HashMap<String, Integer>();
for (var w : words) {
  counts.(w, 1, Integer::);
}

Live Code Lab

JavaMapDemo.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
java count: 3
unique tags: [java, oop, streams]

Check Your Understanding

Score: 0 / 1

1. What does counts.getOrDefault("rust", 0) return if "rust" is not in the map?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind