In Java, HashMap (in java.util, since Java 1.2) stores key/value pairs in a hash table. Every key is unique and maps to exactly one value: put() stores a pair, get() reads the value for a key, and remove() deletes it. With well-behaved keys, these operations take constant time on average, however large the map grows.
It implements the Map interface plus Cloneable and Serializable. A HashMap allows one null key and any number of null values, and it keeps no guaranteed order. The HashMap Methods index lists every guide.
Two rules to remember.
A HashMap is not thread-safe: for shared access use ConcurrentHashMap or a wrapper from Collections.synchronizedMap. Its iterators are fail-fast: adding or removing keys while looping usually throws ConcurrentModificationException, so remove through entrySet() iterators or removeIf.
Syntax
Java Syntax
Import the class, then create a map. Declaring the variable as Map keeps your code flexible:
Java
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> ages = new HashMap<>(); // empty
Map<String, Integer> copy = new HashMap<>(ages); // copy of another map
Map<Integer, String> big = new HashMap<>(1000); // capacity hint, still empty
ages.put("Lina", 29); // int 29 is autoboxed to Integer
Integer a = ages.get("Lina"); // 29
Integer b = ages.get("Omar"); // null (no such key)
Keys and values must be objects, so numbers are stored as Integer, Double, and so on. Java 9 added Map.of(...) for small fixed maps, but those are unmodifiable and reject null; use new HashMap<>() when the map must change.
Reference
How Hashing Works
A HashMap keeps an array of buckets. To store a key, it calls the key's hashCode(), mixes the bits, and uses the result to pick a bucket. To find the key again, it goes straight to that bucket and compares the keys there with equals(). Different keys can land in the same bucket (a collision); they are then kept side by side in that bucket.
Idea
What it means for you
equals / hashCode contract
Keys that are equal must return the same hash code. Override both in your own key classes; String and Integer already do.
Immutable keys
Never change a key after putting it; its hash changes and the entry can no longer be found.
Capacity and load factor
In OpenJDK a new map starts with 16 buckets and a load factor of 0.75: when it holds more than 75% as many entries as buckets, the table doubles and entries are redistributed.
Iteration order
Entries are visited bucket by bucket, so the order depends on hash codes and table size, and can change after a resize.
The 16 and 0.75 defaults are documented, but resizing details and printed orders are implementation details. Since Java 8, a bucket with many colliding keys can switch to a small tree, so even bad hash codes degrade to O(log n) rather than O(n) for comparable keys.
Reference
HashMap vs LinkedHashMap, TreeMap, and Others
All of these implement Map; they differ in order, speed, and thread safety:
Class
Order
Keep in mind
HashMap
None guaranteed
Fastest general-purpose map; one null key allowed
LinkedHashMap
Insertion order (or access order)
A HashMap plus a linked list through the entries; slightly more memory
TreeMap
Sorted by key
O(log n) operations; keys must be comparable; no null key by default
Hashtable
None guaranteed
Legacy synchronized class; no null keys or values
ConcurrentHashMap
None guaranteed
Thread-safe with atomic putIfAbsent, compute, and merge; no null keys or values
Reference
What Is Fast and What Is Slow
Key-based operations jump to one bucket; value-based operations must scan the whole map:
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Interface type. The variable is a Map<String, Integer> and the object a HashMap, so the rest of the code relies only on map operations.
Unordered printing. The first line lists kiwi, fig, mango although mango was added first: the three names hash to buckets 2, 5, and 15, and a HashMap prints bucket by bucket.
Update and delete. Putting kiwi again replaces 4 with 6 and returns the old 4; remove("fig") deletes fig, so containsKey is false and two items remain.
Key/value loop.entrySet() hands out each remaining pair, giving kiwi x6 and mango x10.
Example 2 — Count Letters with Character Keys
Count each letter of "banana" with merge, then read counts with get and getOrDefault.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapCharCount {
public static void main(String[] args) {
String word = "banana";
Map<Character, Integer> counts = new HashMap<>();
for (char c : word.toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
System.out.println(counts);
System.out.println("a appears " + counts.get('a') + " times");
System.out.println("z appears " + counts.getOrDefault('z', 0) + " times");
}
}
Output
{a=3, b=1, n=2}
a appears 3 times
z appears 0 times
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Boxed char keys. Each char from toCharArray() is autoboxed to a Character when it is used as a key.
Count with merge. The first b, n, or a stores 1; every repeat adds 1 with Integer::sum, giving a=3, n=2, b=1.
Why it looks sorted. A Character hashes to its own code (a is 97, b 98, n 110), which puts these letters in buckets 1, 2, and 14, so they happen to print alphabetically.
Missing letter. There is no z, so getOrDefault('z', 0) returns the fallback 0 instead of null.
Example 3 — HashMap vs LinkedHashMap vs TreeMap Order
Put the same four names into three kinds of map and print each one.
Java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class HashMapOrderCompared {
public static void main(String[] args) {
String[] names = {"Zoe", "Adam", "Mia", "Eli"};
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (int i = 0; i < names.length; i++) {
hash.put(names[i], i);
linked.put(names[i], i);
tree.put(names[i], i);
}
System.out.println("HashMap: " + hash);
System.out.println("LinkedHashMap: " + linked);
System.out.println("TreeMap: " + tree);
}
}
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Same data three times. Each map receives the four names with their position in the array as the value.
HashMap: bucket order. The first line follows the hash codes: Adam, Zoe, Eli, and Mia fall into buckets 0, 1, 3, and 4 of the 16-slot table. Adam happens to come first, but the order is neither insertion nor alphabetical (Zoe precedes Eli) and is not guaranteed.
LinkedHashMap: insertion order. It keeps a linked list through its entries, so it prints Zoe, Adam, Mia, Eli exactly as they were added.
TreeMap: sorted order. It keeps keys sorted, so the names appear alphabetically, at the cost of O(log n) lookups.
HashMap is a class in java.util that stores key/value pairs in a hash table. Each key is unique and maps to one value. You look values up by key, usually in constant time. It implements the Map interface.
No. Entries are kept in buckets chosen from the keys' hash codes, and the iteration order is not guaranteed. Use LinkedHashMap for insertion order or TreeMap for sorted keys.
Yes. It allows one null key and any number of null values. Because get() also returns null for a missing key, use containsKey() to tell the two cases apart.
No. Use ConcurrentHashMap for concurrent access, or wrap the map with Collections.synchronizedMap(...) and synchronize manually while iterating.
HashMap finds a key by its hash code and then confirms it with equals(). Equal keys must have equal hash codes, or the map cannot find them. Strings, Integers, and other standard value classes already do this correctly.