Thuta Learning
AdvancedProgrammingbeginner

HashMap

Relax. We'll talk through this in plain words — no textbook voice.

HashMap is a collection that stores data as key-value pairs. With an array or list you look things up by index, but with a HashMap you look things up by key — handy for storing things like username to user role, product code to price, or country to capital city.

java
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> productPrices = new HashMap<String, Integer>();

    productPrices.put("Keyboard", 50);
    productPrices.put("Mouse", 25);
    productPrices.put("Monitor", 200);

    System.out.println(productPrices);
    System.out.println("Mouse price: " + productPrices.get("Mouse"));
    System.out.println("Has Keyboard: " + productPrices.containsKey("Keyboard"));
  }
}

HashMap<String, Integer> is a map that stores String keys and Integer values. You add data with put() and grab a value with get(key). containsKey() checks whether a key exists.

You should see
{Mouse=25, Keyboard=50, Monitor=200} Mouse price: 25 Has Keyboard: true

Real-World Use

HashMap is commonly used for things like user settings, product prices, API response mappings, translation dictionaries, and cache data.

Easy traps

  • If the key's spelling or case is off, you won't find the value. Mouse and mouse are not the same thing.
HashMap | Thuta Learning