Java HashMap getOrDefault() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, getOrDefault(key, defaultValue) returns the value a HashMap holds for key. If there is no mapping for that key, it returns defaultValue instead of null.

It only reads: the default is not stored in the map. That makes it a handy one-line replacement for "get, then check for null", especially for counters and configuration with fallback values.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. getOrDefault was added in Java 8 as a default method of Map; HashMap overrides it with a single lookup.

Syntax

Pass the key and a fallback of the value type.

Java
Map<String, Integer> settings = new HashMap<>();
settings.put("volume", 70);
int v = settings.getOrDefault("volume", 50);   // 70
int b = settings.getOrDefault("bright", 50);   // 50 (not stored)
CallWhat it does
map.getOrDefault(k, d)Value for k, or d when k is missing.
map.getOrDefault(k, 0) + 1The usual counting idiom, paired with put.
map.get(k)Same lookup, but null for a missing key.
map.computeIfAbsent(k, f)Stores the fallback instead of just returning it.

The default value is evaluated before the call, every time, even when the key exists. Pass a constant or a cheap expression.

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V getOrDefault(Object key, V defaultValue)

// Default method in Map<K, V>, overridden by HashMap

Parameters

ParameterDescription
key (Object)The key to look up.
defaultValue (V)Returned when the map has no mapping for key. May be null.

Return Value

Return ValueDescription
VThe stored value (even if it is null), or defaultValue when the key is missing.

Compare with Similar Methods

Reading with a fallback:

MethodHow it differs
get(k)Returns null for a missing key.
computeIfAbsent(k, f)Creates the value and stores it in the map.
putIfAbsent(k, v)Stores v if the key is missing; returns the old value.
merge(k, 1, Integer::sum)A shorter way to count than getOrDefault plus put.

Java Examples

Example 1 — Read Settings with Fallback Values

Two settings are stored; a third falls back to a default without being added.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapGetOrDefaultDemo {
    public static void main(String[] args) {
        Map<String, Integer> settings = new HashMap<>();
        settings.put("fontSize", 18);
        settings.put("volume", 70);

        int fontSize = settings.getOrDefault("fontSize", 14);
        int brightness = settings.getOrDefault("brightness", 50);

        System.out.println("fontSize = " + fontSize);
        System.out.println("brightness = " + brightness);
        System.out.println("brightness stored? " + settings.containsKey("brightness"));
        System.out.println("size = " + settings.size());
    }
}

How It Works

  1. Stored value wins. "fontSize" exists, so its stored 18 is returned and the fallback 14 is ignored.
  2. Fallback for a gap. Nobody set "brightness", so the call returns the supplied 50.
  3. Safe to unbox. Because a non-null default is always available here, assigning the result to an int cannot throw.
  4. Read-only. The map still has two settings and no "brightness" key: getOrDefault never writes.

Example 2 — Count Votes with getOrDefault and put

Tally drink votes, print them sorted with a TreeMap copy, and read a count for an option nobody chose.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapGetOrDefaultCount {
    public static void main(String[] args) {
        String[] votes = {"tea", "coffee", "tea", "juice", "tea", "coffee"};
        Map<String, Integer> tally = new HashMap<>();

        for (String v : votes) {
            tally.put(v, tally.getOrDefault(v, 0) + 1);
        }

        System.out.println("sorted: " + new TreeMap<>(tally));
        System.out.println("water: " + tally.getOrDefault("water", 0));
    }
}

How It Works

  1. Start at zero. The first "tea" is missing, so getOrDefault(v, 0) gives 0 and put stores 1.
  2. Read, add, write back. Later votes read the current count, add one, and put overwrites the old number: tea ends at 3, coffee at 2, juice at 1.
  3. Sorted printing. new TreeMap<>(tally) copies the counts into a map ordered by key, so the printed order is alphabetical and does not depend on hashing.
  4. Zero for unknown options. Asking for "water" returns 0 without adding a water entry to the tally.

Example 3 — A Key Mapped to null Does Not Get the Default

One name has a nickname, one is stored with null, and one is missing.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapGetOrDefaultNull {
    public static void main(String[] args) {
        Map<String, String> nicknames = new HashMap<>();
        nicknames.put("Robert", "Bob");
        nicknames.put("Susan", null);

        System.out.println("Robert: " + nicknames.getOrDefault("Robert", "(none)"));
        System.out.println("Susan: " + nicknames.getOrDefault("Susan", "(none)"));
        System.out.println("Tim: " + nicknames.getOrDefault("Tim", "(none)"));

        String susan = nicknames.get("Susan");
        String shown = susan != null ? susan : "(none)";
        System.out.println("Susan, null-safe: " + shown);
    }
}

How It Works

  1. Normal hit. Robert has a nickname, so "Bob" comes back.
  2. Present but null. Susan is a key in the map, so the stored null is returned; the "(none)" default is only for keys that are absent.
  3. Truly absent. Tim was never added, so this is the one call that returns the default.
  4. Treat null like missing. When a null value should also fall back, read with get and test for null yourself, as the last two lines do.

Frequently Asked Questions

It returns the value stored for a key, or the default you pass when the map has no mapping for that key.
No. It only reads. Use computeIfAbsent() or putIfAbsent() when you want the value stored.
getOrDefault() returns null, because the key is present. The default is used only for missing keys.
Java 8, as a default method of the Map interface.
Yes: map.put(w, map.getOrDefault(w, 0) + 1) works. merge(w, 1, Integer::sum) does the same in one call.

Next: isEmpty()

Check whether the map has no mappings.

isEmpty() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful