Java HashMap size() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, size() returns how many key/value mappings a HashMap currently holds. Each key counts once, because keys are unique: putting an existing key again replaces its value and does not change the size.

A null key and null values count like any other mapping. The size is not the capacity: the internal table usually has more buckets than there are entries.

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.

Syntax

No arguments; returns an int.

Java
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.put("b", 2);
m.put("a", 3);
int n = m.size();   // 2 (the key "a" was replaced, not added)
CallWhat it does
map.size()Number of mappings.
map.size() == 0Same as map.isEmpty().
map.keySet().size()Always equal to map.size().
new HashSet<>(map.values()).size()Number of distinct values.

size() returns a stored counter, so it runs in constant time.

Library declarations
Java
// java.util.HashMap<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 or more).

Compare with Similar Methods

Counting and emptiness:

MethodHow it differs
isEmpty()true when the size is 0.
clear()Sets the size back to 0.
keySet()A view whose size always equals the map's.
values()Same count, but may contain duplicates.

Java Examples

Example 1 — What Changes size() and What Does Not

Count page visits, overwrite a key, add a null key, and remove both a present and a missing key.

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

public class HashMapSizeDemo {
    public static void main(String[] args) {
        Map<String, Integer> visits = new HashMap<>();
        System.out.println("start: " + visits.size());

        visits.put("home", 3);
        visits.put("about", 1);
        visits.put("home", 4);
        System.out.println("after 3 puts: " + visits.size());

        visits.put(null, 0);
        System.out.println("with null key: " + visits.size());

        visits.remove("about");
        visits.remove("contact");
        System.out.println("after removes: " + visits.size());
    }
}

How It Works

  1. Empty start. A new HashMap holds no mappings, so the size is 0.
  2. Overwrite is not an add. The second "home" replaces 3 with 4, so three put calls produce only two mappings.
  3. null key counts. HashMap accepts one null key, and it raises the size to 3 like any other key.
  4. Only real removals count. Removing "about" drops the size to 2; removing the never-added "contact" changes nothing.

Example 2 — Sizes of the Views and Distinct Values

Three things, two of them blue: compare the map size with its views and with the number of distinct colors.

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

public class HashMapSizeViews {
    public static void main(String[] args) {
        Map<String, String> colors = new HashMap<>();
        colors.put("sky", "blue");
        colors.put("sea", "blue");
        colors.put("leaf", "green");

        System.out.println("map size: " + colors.size());
        System.out.println("keySet size: " + colors.keySet().size());
        System.out.println("values size: " + colors.values().size());
        System.out.println("entrySet size: " + colors.entrySet().size());
        System.out.println("distinct values: " + new HashSet<>(colors.values()).size());
    }
}

How It Works

  1. One count, three views. keySet(), values(), and entrySet() are views of the same map, so all report the map's size, 3.
  2. Values may repeat. The values view holds "blue" twice, because two different keys map to it.
  3. Remove duplicates. Copying the values into a HashSet keeps each color once, leaving 2.
  4. Keys never repeat. There is no need to deduplicate the keys: a map cannot hold the same key twice.

Example 3 — Count Unique Visitors in a Log

Seven log lines from four users: the map size is the number of distinct users.

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

public class HashMapSizeDistinct {
    public static void main(String[] args) {
        String[] log = {"u1", "u2", "u1", "u3", "u2", "u1", "u4"};
        Map<String, Integer> perUser = new HashMap<>();
        for (String user : log) {
            perUser.merge(user, 1, Integer::sum);
        }

        int unique = perUser.size();
        System.out.println("visits: " + log.length);
        System.out.println("unique visitors: " + unique);
        System.out.println("repeat visits: " + (log.length - unique));
        System.out.println("u1 share: " + (perUser.get("u1") * 100 / log.length) + "%");
    }
}

How It Works

  1. One entry per user. merge(user, 1, Integer::sum) creates an entry the first time a user appears and adds one on every later visit.
  2. Size means distinct. Seven lines mention only u1 to u4, so the map ends with four keys.
  3. Derived numbers. 7 visits minus 4 first visits leaves 3 repeat visits.
  4. Integer math. u1 appears 3 times; 3 * 100 / 7 uses int division and truncates 42.85 to 42.

Frequently Asked Questions

Call map.size(). It returns the number of key/value mappings.
No. The second put replaces the value, so the size stays the same.
Yes. Every mapping counts, including a null key and keys mapped to null.
Size is the number of mappings. Capacity is the number of buckets in the internal table, which grows automatically and cannot be read through the public API.
No. HashMap keeps a counter, so size() takes the same time for any map.

Next: values()

Get a live Collection view of all values.

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

9 people found this page helpful