SwadhyAI Notes

All Java notes

Java HashMap Methods Reference

›Short versionOpen if you only have a minute.
  • HashMap stores one value per key. put on a key that is already present replaces the value.
  • One null key is allowed. Any number of values may be null.
  • get returns null both when the key is missing and when the key is mapped to null.
  • containsKey tells those two cases apart. getOrDefault does not replace a stored null.
  • Iteration order is not insertion order. LinkedHashMap keeps insertion order. TreeMap keeps key order.
  • A key whose hashCode changes after insertion is no longer found by get.

HashMap stores values by unique keys and uses hashCode plus equals to find buckets. It is ideal for fast lookup by meaningful identifiers.

Methods

APIParametersReturnsBehaviorWatch for
put(K key, V value)Key and value.Previous value for key, or null.Adds or replaces a mapping.Null return can mean no old mapping or an old null value.
get(Object key)Lookup key.Mapped value or null.Finds by hashCode then equals.Use containsKey() to distinguish missing key from null value.
getOrDefault(Object key, V defaultValue)Key and fallback value.Mapped value or fallback.Avoids explicit contains check for simple defaults.If key maps to null, null is returned instead of default.
computeIfAbsent(K key, Function mapper)Key and function that creates a value.Existing or newly computed value.Creates missing values lazily.Mapper should not mutate the same map in surprising ways.
remove(Object key)Key to delete.Removed value or null.Deletes a mapping if present.Use remove(key, value) when value must match too.
entrySet()None.Set of Map.Entry views.Efficient way to iterate keys and values together.Entries are backed by the map.

Which call fits

OptionBest forTradeoff
HashMapFast unordered lookup by key.No predictable iteration order.
LinkedHashMapLookup with insertion or access order.Slightly more memory overhead.
TreeMapSorted keys and range queries.O(log n) operations instead of average O(1).

Examples

Count words

java
HashMap<String, Integer> counts = new HashMap<>();

for (String word : List.of("java", "map", "java")) {
    counts.put(word, counts.getOrDefault(word, 0) + 1);
}

System.out.println(counts.get("java")); // 2

Group with computeIfAbsent

java
HashMap<String, ArrayList<String>> byGrade = new HashMap<>();
byGrade.computeIfAbsent("A", grade -> new ArrayList<>()).add("Ada");
byGrade.computeIfAbsent("A", grade -> new ArrayList<>()).add("Grace");

map.put("score", null); then map.get("score") and map.getOrDefault("score", 0). What does each call return?

Both return null. The key is present, and its value is null, so getOrDefault does not substitute 0. map.containsKey("score") is true. For a key that was never inserted, get is null, containsKey is false, and getOrDefault returns the fallback.