Java TreeMap getOrDefault() Method

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

Definition

In Java, getOrDefault(key, defaultValue) returns the value stored under key in a TreeMap, or defaultValue if the key is not present. It never stores the default.

It removes the "get, then check for null" step, and is handy with numbers, where a missing price can count as 0. A key that is present but mapped to null returns null, not the default.

An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe. TreeMap inherits the Map default implementation, which uses one get plus a containsKey only when the value is null.

Syntax

Pass the key and the value to use when it is missing.

Java
TreeMap<String, Integer> priceInCents = new TreeMap<>();
int p = priceInCents.getOrDefault("caviar", 0);   // 0 (missing key)
CallWhat it does
map.getOrDefault(k, 0)Missing numbers count as 0.
map.getOrDefault(k, "free")A placeholder text for empty slots.
map.getOrDefault(k, d) == dNot a reliable "missing" test; use containsKey.

Unlike computeIfAbsent() or putIfAbsent(), the default value is only returned, never stored, so the map size does not change.

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

// Default method of Map<K, V> since Java 8 (inherited by TreeMap)

Parameters

ParameterDescription
key (Object)The key to look up. Not null under natural ordering.
defaultValue (V)Returned when the key is absent. May be null.

Return Value

Return ValueDescription
VThe stored value (even if it is null).
defaultValueThe key is not in the map.

Compare with Similar Methods

Reading with a fallback:

MethodHow it differs
get(k)Returns null for a missing key.
computeIfAbsent(k, f)Creates and stores the missing value.
merge(k, v, f)Use it to count; getOrDefault plus put needs two lookups.
HashMap.getOrDefaultSame behaviour on an unordered map.

Java Examples

Example 1 — Add Up a Cart With Unknown Items

Prices are stored in cents. An item that is not in the price list costs 0.

Java
import java.util.TreeMap;

public class TreeMapGetOrDefaultCart {
    public static void main(String[] args) {
        TreeMap<String, Integer> priceInCents = new TreeMap<>();
        priceInCents.put("apple", 45);
        priceInCents.put("bread", 250);
        priceInCents.put("milk", 119);

        String[] cart = {"milk", "apple", "caviar", "apple"};
        int total = 0;
        for (String item : cart) {
            int price = priceInCents.getOrDefault(item, 0);
            System.out.println(item + ": " + price);
            total += price;
        }
        System.out.println("total cents: " + total);
    }
}

How It Works

  1. Known items. milk and apple are keys, so their stored prices 119 and 45 are returned.
  2. Safe unboxing. caviar is missing, so the default 0 comes back; assigning it to int is safe, whereas get would give null and crash.
  3. The sum. 119 + 45 + 0 + 45 = 209 cents, and the price list still holds exactly three items.

Example 2 — A Stored null Is Returned as null

Dr. Ito is in the map with no room yet. Compare her with Dr. Fox, who is not in the map at all.

Java
import java.util.TreeMap;

public class TreeMapGetOrDefaultNullValue {
    public static void main(String[] args) {
        TreeMap<String, String> roomOf = new TreeMap<>();
        roomOf.put("Dr. Lee", "B204");
        roomOf.put("Dr. Ito", null);

        System.out.println("Dr. Lee -> " + roomOf.getOrDefault("Dr. Lee", "unknown"));
        System.out.println("Dr. Ito -> " + roomOf.getOrDefault("Dr. Ito", "unknown"));
        System.out.println("Dr. Fox -> " + roomOf.getOrDefault("Dr. Fox", "unknown"));
    }
}

How It Works

  1. Normal value. Dr. Lee maps to B204, so that is returned and the default is ignored.
  2. Present but null. Dr. Ito's key exists, so getOrDefault returns the stored null rather than "unknown".
  3. Absent key. Only Dr. Fox, who has no entry at all, receives the fallback text.

Example 3 — Print a Day Plan With Free Hours

Only booked hours are stored; every other hour shows as free.

Java
import java.util.TreeMap;

public class TreeMapGetOrDefaultSchedule {
    public static void main(String[] args) {
        TreeMap<Integer, String> bookings = new TreeMap<>();
        bookings.put(10, "Team sync");
        bookings.put(12, "Lunch talk");

        for (int hour = 9; hour <= 12; hour++) {
            System.out.println(hour + ":00 " + bookings.getOrDefault(hour, "free"));
        }
        System.out.println("stored bookings: " + bookings.size());
    }
}

How It Works

  1. Sparse storage. The map holds only hours 10 and 12; there is no need to store "free" for every empty hour.
  2. Autoboxed lookup key. The loop variable hour is an int; it is boxed to Integer and compared with the stored keys.
  3. Read-only fallback. After printing four hours the map still has 2 bookings, because getOrDefault never inserts the default.

Frequently Asked Questions

null. The default is used only when the key is missing.
No. It only returns the default; the map is unchanged. Use computeIfAbsent or putIfAbsent to store it.
Java 8, as a default method of the Map interface. TreeMap inherits it.
It does the same O(log n) lookup. Only when the found value is null does it also check containsKey.
Yes: map.put(k, map.getOrDefault(k, 0) + 1). merge(k, 1, Integer::sum) does the same in one call.

Next: headMap()

A live view of the keys below a limit.

headMap() 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