Script Valley
Java: Complete Language Course
Java Collections FrameworkLesson 3.2

Java HashMap and HashSet for fast lookups

HashMap, HashSet, Map interface, Set interface, key-value pairs, hash function, O(1) lookup, duplicate handling, null keys, entrySet iteration

HashMap and HashSet

Hash-based collections trade memory for speed โ€” O(1) average-case lookup, insert, and delete regardless of collection size.

HashMap โ€” Key to Value

import java.util.HashMap;
import java.util.Map;

Map wordCount = new HashMap<>();
wordCount.put("java", 5);
wordCount.put("python", 3);
wordCount.put("java", 7);  // overwrites previous value

System.out.println(wordCount.get("java")); // 7
System.out.println(wordCount.getOrDefault("go", 0)); // 0

// Iterate all entries
for (Map.Entry e : wordCount.entrySet()) {
    System.out.println(e.getKey() + " โ†’ " + e.getValue());
}

HashSet โ€” Unique Elements

import java.util.HashSet;
import java.util.Set;

Set seen = new HashSet<>();
seen.add("alpha");
seen.add("beta");
seen.add("alpha"); // silently ignored โ€” duplicate

System.out.println(seen.size()); // 2
System.out.println(seen.contains("beta")); // true

Keys in a HashMap must implement hashCode() and equals() correctly. All standard Java types (String, Integer, etc.) already do. When you use a custom class as a key, you must override both or lookups will fail silently โ€” two logically equal objects may hash to different buckets.

HashMap allows one null key and multiple null values. Insertion order is not guaranteed. Use LinkedHashMap to preserve insertion order, or TreeMap for natural sorted order at the cost of O(log n) operations.

For read-heavy concurrent scenarios, consider ConcurrentHashMap instead of HashMap with external synchronization. It allows concurrent reads and uses segment-level locking for writes, providing significantly better throughput under contention.

Up next

Java generics and type-safe collections

Sign in to track progress

Java HashMap and HashSet for fast lookups โ€” Java Collections Framework โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley