Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

HashMap

A map backed by a hash table: fast lookup by key, no guaranteed order.

Available since: Java 1.2

Syntax

public class HashMap<K, V> implements Map<K, V>

Examples

A phone book:

void main() {
    Map<String, String> phones = new HashMap<>();
    phones.put("Anna", "555-0101");
    phones.put("Oleg", "555-0102");
    IO.println(phones.get("Anna"));
    IO.println(phones.size());
}

Output:

555-0101
2

Counting words:

void main() {
    Map<String, Integer> counts = new HashMap<>();
    for (String w : "a b a c b a".split(" ")) {
        counts.merge(w, 1, Integer::sum);
    }
    IO.println(counts.get("a") + " " + counts.get("b") + " " + counts.get("c"));
}

Output:

3 2 1

Notes

get(), put() and containsKey() run in constant time. The iteration order depends on key hashes — use LinkedHashMap for insertion order and TreeMap for sorted order. It allows one null key and null values. It is not thread-safe — in concurrent code use ConcurrentHashMap.

See also

  • LinkedHashMap — A map that remembers the insertion order of keys.
  • TreeMap — A map whose keys are always sorted.
  • Map.put() — Stores a value under a key, replacing the old one.
  • Map.get() — Returns the value for a key, or `null`.
  • ConcurrentHashMap — A thread-safe map for concurrent use from many threads.

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.