Hash Maps in C++, Java, JavaScript & Python
Every language ships a battle-tested hash map so you never have to build one in real code: C++ has std::unordered_map, Java has HashMap, JavaScript has Map, and Python has the built-in dict. They all give O(1) average insert, lookup, update, and delete by key — this page shows the idiomatic way to use each one. Pick your language with the switcher and these become muscle memory.
Create, insert, and read
#include <unordered_map>
#include <string>
std::unordered_map<std::string, int> m;
m["apple"] = 3; // insert or overwrite
m["apple"] += 1; // now 4
int n = m["apple"]; // read -> 4 (inserts 0 if missing!)
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> m = new HashMap<>();
m.put("apple", 3); // insert or overwrite
m.merge("apple", 1, Integer::sum); // now 4
int n = m.get("apple"); // read -> 4 (null if missing)
const m = new Map();
m.set("apple", 3); // insert or overwrite
m.set("apple", m.get("apple") + 1); // now 4
const n = m.get("apple"); // read -> 4 (undefined if missing)
m = {}
m["apple"] = 3 # insert or overwrite
m["apple"] += 1 # now 4
n = m["apple"] # read -> 4 (KeyError if missing)
Check existence before reading
Reading a missing key behaves differently in each language — unordered_map::operator[] and Python raise or auto-insert, so check membership first.
if (m.count("apple")) { // or m.find("apple") != m.end()
int v = m["apple"];
}
// Safe read without inserting:
auto it = m.find("banana");
bool present = (it != m.end());
if (m.containsKey("apple")) {
int v = m.get("apple");
}
// Safe read with a default:
int v = m.getOrDefault("banana", 0);
if (m.has("apple")) {
const v = m.get("apple");
}
// Safe read with a default:
const v = m.get("banana") ?? 0;
if "apple" in m:
v = m["apple"]
# Safe read with a default:
v = m.get("banana", 0)
Update, delete, and size
m["apple"] = 10; // update
m.erase("apple"); // delete (no-op if absent)
size_t size = m.size();
m.put("apple", 10); // update
m.remove("apple"); // delete (no-op if absent)
int size = m.size();
m.set("apple", 10); // update
m.delete("apple"); // delete (returns false if absent)
const size = m.size; // property, not a method
m["apple"] = 10 # update
m.pop("apple", None) # delete safely (None default avoids KeyError)
size = len(m)
Iterate over entries
Hash maps are unordered — do not rely on iteration order for logic. (JS Map and modern Python dict happen to preserve insertion order, but C++ unordered_map and Java HashMap give no guarantee.)
for (const auto& [key, val] : m) {
// use key, val
}
for (Map.Entry<String, Integer> e : m.entrySet()) {
String key = e.getKey();
int val = e.getValue();
}
for (const [key, val] of m) {
// use key, val
}
for key, val in m.items():
pass # use key, val
A real task: count word frequencies
The most common hash-map job — tally how many times each item appears, in one O(n) pass:
#include <unordered_map>
#include <vector>
#include <string>
std::unordered_map<std::string, int> countWords(const std::vector<std::string>& words) {
std::unordered_map<std::string, int> freq;
for (const auto& w : words) freq[w]++; // missing key starts at 0
return freq;
}
import java.util.*;
Map<String, Integer> countWords(List<String> words) {
Map<String, Integer> freq = new HashMap<>();
for (String w : words) freq.merge(w, 1, Integer::sum);
return freq;
}
function countWords(words) {
const freq = new Map();
for (const w of words) freq.set(w, (freq.get(w) ?? 0) + 1);
return freq;
}
from collections import Counter
def count_words(words):
return Counter(words) # dict subclass: word -> count
For beginners: When you need a counter or a default value, reach for the language’s helper — Java’s
merge/getOrDefault, JS’s?? 0, Python’scollections.Counterordefaultdict(int). They remove the “is the key there yet?” boilerplate.
Going deeper: Need keys in sorted order? Use an ordered structure instead: C++
std::map(a balanced tree, O(log n)), JavaTreeMap, or sort the keys on demand. JS and Python have no built-in sorted map — sort the keys yourself. See choosing the right data structure.
Using custom objects as keys
Primitive and string keys just work. For a custom type you must tell the map how to hash and compare it: provide std::hash + operator== in C++, override hashCode() + equals() in Java, and define __hash__ + __eq__ (and make it immutable) in Python. JS Map keys compare by reference, so two equal-looking objects are different keys — use a string key instead.
Next: the set side of the family — hash sets.