Labs ICT
โญ Pro Login

HashMap

An ArrayList is great when you have a list of items and you access them by index. But what if you want to look something up by a key instead of a number? Like looking up a phone number by a person's name.

That is exactly what a HashMap does. It stores key-value pairs. You give it a key, it gives you the value. Think of it as a real dictionary โ€” you look up a word (key) and get the definition (value).

Creating a HashMap

You need to specify two types โ€” the key type and the value type โ€” inside angle brackets.

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap ages = new HashMap<>();
  }
}

This creates a map that uses String keys and Integer values. You would use it to store things like "Amina" -> 25.

Put and Get

put() adds a key-value pair. get() retrieves the value for a given key.

import java.util.HashMap;

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

    ages.put("Amina", 25);
    ages.put("Musa", 30);
    ages.put("Fatima", 22);

    System.out.println(ages.get("Amina"));
    System.out.println(ages.get("Musa"));
  }
}

ages.get("Amina") returns 25. If you try to get a key that does not exist, you get null back.

Checking for a Key

Before calling get(), you might want to check if a key exists. Use containsKey().

import java.util.HashMap;

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

    ages.put("Amina", 25);
    ages.put("Musa", 30);

    if (ages.containsKey("Amina")) {
      System.out.println("Amina is " + ages.get("Amina"));
    }

    if (ages.containsKey("John")) {
      System.out.println("John is " + ages.get("John"));
    } else {
      System.out.println("John not found");
    }
  }
}

containsKey() returns a boolean. It is a safe way to check before accessing, especially when you are not sure what keys exist.

Iterating Over a HashMap

You can get all the keys using keySet() and then loop through them.

import java.util.HashMap;

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

    ages.put("Amina", 25);
    ages.put("Musa", 30);
    ages.put("Fatima", 22);

    for (String name : ages.keySet()) {
      System.out.println(name + " is " + ages.get(name));
    }
  }
}

keySet() returns a set of all the keys. You loop through each key and use get() to pull the corresponding value. This is the standard way to iterate over a HashMap.

๐Ÿงช Quick Quiz

How do you store key-value pairs in Java?