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)
Call
What it does
map.size()
Number of mappings.
map.size() == 0
Same 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>
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.
Size means distinct. Seven lines mention only u1 to u4, so the map ends with four keys.
Derived numbers. 7 visits minus 4 first visits leaves 3 repeat visits.
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.