Skip to content
DSA hashing 8 min read

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!)

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());

Update, delete, and size

m["apple"] = 10;     // update
m.erase("apple");    // delete (no-op if absent)
size_t size = m.size();

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
}

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;
}

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’s collections.Counter or defaultdict(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)), Java TreeMap, 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.

Last updated June 25, 2026
Was this helpful?