Java HashMap

Beginner
8 min read
Updated: Nov 2026
3 examples
java.util.HashMap

Definition and Usage

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.

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.

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.

IdeaWhat it means for you
equals / hashCode contractKeys that are equal must return the same hash code. Override both in your own key classes; String and Integer already do.
Immutable keysNever change a key after putting it; its hash changes and the entry can no longer be found.
Capacity and load factorIn 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 orderEntries 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.

HashMap vs LinkedHashMap, TreeMap, and Others

All of these implement Map; they differ in order, speed, and thread safety:

ClassOrderKeep in mind
HashMapNone guaranteedFastest general-purpose map; one null key allowed
LinkedHashMapInsertion order (or access order)A HashMap plus a linked list through the entries; slightly more memory
TreeMapSorted by keyO(log n) operations; keys must be comparable; no null key by default
HashtableNone guaranteedLegacy synchronized class; no null keys or values
ConcurrentHashMapNone guaranteedThread-safe with atomic putIfAbsent, compute, and merge; no null keys or values

What Is Fast and What Is Slow

Key-based operations jump to one bucket; value-based operations must scan the whole map:

OperationCostWhy
get(k), put(k, v), containsKey(k), remove(k)Constant on averageOne bucket is checked; a resize occasionally copies the table
size(), isEmpty()ConstantA stored counter
containsValue(v)Grows with the mapValues are not hashed, so every entry is checked
Looping with entrySet() or forEach()Grows with the mapEvery bucket and entry is visited

Java Examples

Example 1 — Create, Read, Update, Remove, and Loop

A small fruit stock: add three items, read one, update one, remove one, and loop over what is left.

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

public class HashMapBasics {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("mango", 10);
        stock.put("kiwi", 4);
        stock.put("fig", 7);

        System.out.println(stock);
        System.out.println("kiwi: " + stock.get("kiwi"));

        Integer old = stock.put("kiwi", 6);
        stock.remove("fig");
        System.out.println("kiwi was " + old + ", fig left? " + stock.containsKey("fig") + ", size " + stock.size());

        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            System.out.println(e.getKey() + " x" + e.getValue());
        }
    }
}

How It Works

  1. 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.
  2. 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.
  3. 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.
  4. 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");
    }
}

How It Works

  1. Boxed char keys. Each char from toCharArray() is autoboxed to a Character when it is used as a key.
  2. 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.
  3. 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.
  4. 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);
    }
}

How It Works

  1. Same data three times. Each map receives the four names with their position in the array as the value.
  2. 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.
  3. LinkedHashMap: insertion order. It keeps a linked list through its entries, so it prints Zoe, Adam, Mia, Eli exactly as they were added.
  4. TreeMap: sorted order. It keeps keys sorted, so the names appear alphabetically, at the cost of O(log n) lookups.

Next: Java HashMap Methods by Group

Full list with short descriptions: Java HashMap Methods index (/java/hashmap/method).

Frequently Asked Questions

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.

Browse every HashMap method

Open the methods index for categorized guides with examples and FAQs.

HashMap Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful