HashMap (Java)

A HashMap stores data as key–value pairs, letting you look up a value quickly by its key instead of by position. It is Java's equivalent of a Python dictionary or a JavaScript object/Map.

Java

You declare a HashMap with the types of its keys and values, like HashMap<String, Integer>. Use put() to add a pair, get() to retrieve a value by key, and containsKey() to check if a key exists.

A HashMap does not keep its entries in any particular order. Use LinkedHashMap if you need insertion order.

Examples

Java

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Ana", 30);
        ages.put("Ben", 25);
        System.out.println(ages.get("Ana"));
    }
}

Output:

30

Learn it in a lesson

See also

Back to the Dictionary