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.
