Codectionary / Developer documentation / Java

HashMap

HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).

Syntax

HashMap<KeyType, ValueType> map = new HashMap<>();

Examples

Creating and Adding Entries

Building a HashMap and adding key-value pairs.

import java.util.HashMap;

HashMap<String, Integer> ages = new HashMap<>();
ages.put("John", 21);
ages.put("Zain", 22);
ages.put("Jamal", 20);

System.out.println(ages);              // {John=21, Zain=22, Jamal=20} (order not guaranteed)
System.out.println(ages.get("Zain"));   // 22

Checking, Updating, and Removing

Common operations for working with map entries.

import java.util.HashMap;

HashMap<String, Integer> stock = new HashMap<>();
stock.put("apples", 50);
stock.put("bananas", 30);

System.out.println(stock.containsKey("apples"));  // true
System.out.println(stock.getOrDefault("mango", 0)); // 0 - safe default

stock.put("apples", 45);  // overwrites the existing value
stock.remove("bananas");

System.out.println(stock);  // {apples=45}

Iterating Over a HashMap

Looping through keys, values, or both together.

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

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);

for (String key : scores.keySet()) {
    System.out.println(key + ": " + scores.get(key));
}

for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Useful HashMap Methods

Modern convenience methods like putIfAbsent, compute, and merge.

import java.util.HashMap;

HashMap<String, Integer> wordCount = new HashMap<>();
String[] words = {"apple", "banana", "apple", "cherry", "apple"};

for (String word : words) {
    wordCount.merge(word, 1, Integer::sum);  // increments count, or sets to 1 if new
}

System.out.println(wordCount);  // {banana=1, cherry=1, apple=3}

Best practices

  • Use getOrDefault() or putIfAbsent() instead of manual containsKey() + get() checks, for cleaner and more efficient code
  • Use merge() or compute() for update-in-place patterns like counting occurrences, rather than a manual get-then-put sequence
  • Choose LinkedHashMap if you need predictable insertion-order iteration, or TreeMap if you need keys kept in sorted order
  • Always override equals() and hashCode() properly on any custom class you use as a HashMap key, or lookups will not behave correctly

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading