Lesson 42 +10 XP

Java HashMap

Java HashMap

A HashMap stores items in key/value pairs. You look up a value by its key, like a phone book maps a name to a number.

Creating a HashMap

import java.util.HashMap;

HashMap<String, String> capitalCities = new HashMap<String, String>();

The two types are the key type and the value type.

Adding items

capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");

Common methods

MethodWhat it does
put(key, value)Adds or updates a pair
get(key)Returns the value for a key
remove(key)Deletes a pair
size()Number of pairs
containsKey(key)Checks if a key exists

Reading a value

System.out.println(capitalCities.get("England")); // London

Loop through keys

for (String i : capitalCities.keySet()) {
  System.out.println(i);
}

TL;DR

  • HashMap stores key/value pairs.
  • put adds, get reads by key.
  • keySet() returns the keys for looping.