Java 25 (LTS) reference · 10 entries

Java Map and HashMap Methods

Map and HashMap methods: put(), get(), getOrDefault(), containsKey(), merge(), computeIfAbsent(), entrySet() and Map.of(), with counting and grouping examples.

HashMap has no defined order, so examples print through a TreeMap (sorted by key) or use a LinkedHashMap (insertion order) to keep output predictable.

NameDescriptionSince
Map.of() Create an immutable map from key-value pairs (up to 10 pairs; Map.ofEntries() for more). No null keys or values. Java 9
map.put() Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null. Java 1.0
map.get() Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls. Java 1.0
map.getOrDefault() Return the value for a key, or a default value if the key isn't present. Avoids null checks. Java 8
map.containsKey() Return true if the map has an entry for the key, even when its value is null. O(1) for HashMap. Java 1.0
map.remove() Remove the entry for a key and return its value (or null). remove(key, value) only removes a matching pair. Java 1.0
map.putIfAbsent() Add a key-value pair only if the key is missing (or mapped to null). Returns the existing value otherwise. Java 8
map.merge() Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values. Java 8
map.computeIfAbsent() Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping. Java 8
map.entrySet() Return the map's entries (key-value pairs) for looping over keys and values together. Java 1.0

Was this page helpful?