Java HashMap

A HashMap stores data as key and value pairs. Give the map a key and it returns the matching value almost instantly. Each key appears once in the map.

A Phone Contacts Example

Your phone stores a name and a number together. Type "Asha" and the phone shows her number without scanning the whole list. The name acts as the key. The number acts as the value. A HashMap works the same way.

Diagram: Key and Value Pairs

   Key        Value
 +--------+  +-----------+
 | "Asha" |->| 98100 1111|
 | "Ravi" |->| 98100 2222|
 | "Neha" |->| 98100 3333|
 +--------+  +-----------+

Creating a HashMap

import java.util.HashMap;

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Asha", 21);
ages.put("Ravi", 25);
ages.put("Neha", 23);

The first type inside the brackets belongs to the key. The second type belongs to the value.

Everyday Methods

Reading Values

System.out.println(ages.get("Ravi"));              // 25
System.out.println(ages.getOrDefault("Tina", 0));  // 0
System.out.println(ages.containsKey("Neha"));      // true
System.out.println(ages.containsValue(30));        // false

Changing and Removing

ages.put("Ravi", 26);   // replaces the old value
ages.remove("Neha");
System.out.println(ages.size());   // 2

Putting an existing key replaces its value. A key never appears twice.

Looping Through a Map

for (String name : ages.keySet()) {
    System.out.println(name);
}
for (int age : ages.values()) {
    System.out.println(age);
}
for (HashMap.Entry<String, Integer> e : ages.entrySet()) {
    System.out.println(e.getKey() + " is " + e.getValue());
}

How Hashing Works

A HashMap does not search each pair. It turns the key into a number called a hash code. The number points to a slot called a bucket. Java opens that one bucket and finds the pair.

key "Ravi"
   |
   | hashCode() -> number
   v
+--------+--------+--------+--------+
| bucket | bucket | bucket | bucket |
|   0    |   1    |   2    |   3    |
+--------+---+----+--------+--------+
             |
          Ravi=25

Two keys sometimes land in one bucket. Java stores both there and uses the equals method to pick the right one.

Real Example: Word Counter

A program counts how often each word appears in a sentence. The word is the key. The count is the value.

String[] words = {"tea", "milk", "tea", "sugar", "tea"};
HashMap<String, Integer> count = new HashMap<>();

for (String w : words) {
    count.put(w, count.getOrDefault(w, 0) + 1);
}
System.out.println(count.get("tea"));   // 3

Important Facts

FactDetail
OrderHashMap does not keep insertion order
Duplicate keysNot allowed, the new value wins
NullOne null key and many null values allowed
SpeedReads and writes run fast on average

Custom Keys

Objects that you write need the equals and hashCode methods before they work as keys. String and Integer already include both methods, so they make safe keys.

Common Mistakes

  • Expecting items to print in the order you added them
  • Using a changeable object as a key and changing it later
  • Calling get on a missing key and receiving null
  • Forgetting that a key accepts only one value

Other Map Types

Java offers other maps for special needs. LinkedHashMap remembers insertion order. TreeMap keeps keys sorted from smallest to largest. Pick HashMap first and switch only when you need order.

MapOrder of Keys
HashMapNo promised order
LinkedHashMapInsertion order
TreeMapSorted order

Quick Summary

  • HashMap stores key and value pairs
  • put, get, containsKey, and remove cover the basics
  • Hashing finds a pair without scanning the map