Java TreeMap size() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, size() returns how many key/value mappings a TreeMap holds. Each key counts once, no matter how many times it was put; replacing a value never changes the size.

For the map itself the count is stored in a field and updated on every insert and removal, so size() runs in constant time. On a range view such as headMap, the entries in range are counted on each call.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. 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.

Syntax

Call it on the map or on a view.

Java
TreeMap<Integer, String> spots = new TreeMap<>();
spots.put(4, "KA-01");
int n = spots.size();   // 1
CallWhat it does
map.size()Number of mappings.
map.size() == 0Same as map.isEmpty().
map.headMap(k).size()How many keys are below k.

The result is an int. A map with more than Integer.MAX_VALUE entries would report Integer.MAX_VALUE, which is not a concern for normal programs.

Library declarations
Java
// java.util.TreeMap<K, V>
public int size()

// Declared in Map<K, V>

Parameters

ParameterDescription
Nonesize() takes no parameters.

Return Value

Return ValueDescription
intThe number of key/value mappings (0 for an empty map).

Compare with Similar Methods

Size-related calls:

MethodHow it differs
isEmpty()Clearer than size() == 0.
headMap(k)Its size() counts the keys below k.
keySet()The keys themselves; its size equals the map's.
HashMap.size()Also a stored counter.

Java Examples

Example 1 — Count Occupied Parking Spots

Spot numbers are keys. Re-using a spot and removing a missing spot both leave the count alone.

Java
import java.util.TreeMap;

public class TreeMapSizeParking {
    public static void main(String[] args) {
        TreeMap<Integer, String> spots = new TreeMap<>();
        System.out.println("empty garage: " + spots.size());
        spots.put(4, "KA-01");
        spots.put(1, "TN-22");
        spots.put(4, "MH-12");
        System.out.println("after 3 puts: " + spots.size());
        spots.remove(1);
        spots.remove(9);
        System.out.println("after removing 1 and 9: " + spots.size());
    }
}

How It Works

  1. Starts at zero. A new TreeMap has no mappings.
  2. Spot 4 reused. The third put replaces the car in spot 4 instead of adding an entry, so three calls give a size of 2.
  3. Removing nothing. Spot 1 is freed, but spot 9 never existed, so only one removal counts and the size ends at 1.

Example 2 — A headMap's Size Follows the Map

Keep a view of all orders below 50 and watch its size after new orders arrive.

Java
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapSizeOfView {
    public static void main(String[] args) {
        TreeMap<Integer, String> orders = new TreeMap<>();
        orders.put(5, "small");
        orders.put(40, "medium");
        SortedMap<Integer, String> under50 = orders.headMap(50);
        System.out.println("orders under 50: " + under50.size());

        orders.put(12, "small");
        orders.put(75, "large");
        System.out.println("orders under 50: " + under50.size() + " of " + orders.size());
    }
}

How It Works

  1. View created once. under50 covers order values below 50; at first that is 5 and 40.
  2. New data flows in. 12 falls inside the range and 75 outside it, so the view now counts 3 while the map holds 4.
  3. No refresh needed. The view was never rebuilt: it reads the map each time, which is what "live view" means.

Example 3 — Count Guests With and Without Case Sensitivity

The same five names go into a natural and a case-insensitive map.

Java
import java.util.TreeMap;

public class TreeMapSizeIgnoreCase {
    public static void main(String[] args) {
        String[] guests = {"Tom", "tom", "Eve", "TOM", "eve"};
        TreeMap<String, Boolean> exact = new TreeMap<>();
        TreeMap<String, Boolean> relaxed = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        for (String g : guests) {
            exact.put(g, true);
            relaxed.put(g, true);
        }
        System.out.println("exact size: " + exact.size() + " " + exact.keySet());
        System.out.println("relaxed size: " + relaxed.size() + " " + relaxed.keySet());
    }
}

How It Works

  1. Five distinct strings. Under natural ordering every spelling is a separate key, sorted with uppercase letters first (TOM before Tom because 'O' < 'o').
  2. Two people. The case-insensitive comparator folds Tom/tom/TOM and Eve/eve together, so only 2 mappings exist.
  3. First spellings kept. The relaxed map lists Eve and Tom, the first spelling of each name that was put.

Frequently Asked Questions

Constant time for the map itself, because the count is kept in a field. Counting a range view walks the entries in its range.
No. Only new keys add to the size; replacing a value leaves it unchanged.
Some keys were equal according to the comparator (or compareTo), so later puts replaced values instead of adding keys.
Yes. A key mapped to null is a normal mapping and counts once.
Yes. isEmpty() is easier to read and does the same check.

Next: subMap()

A live view of the keys between two bounds.

subMap() 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.

12 people found this page helpful