CKTIS / Java
Map.size() — Count entries in a map
`Map.size()` returns the current number of key–value mappings as an `int`. Replacing the value for an existing key does not increase the size.
Version: Java SE 21
Syntax
int size()Map.size is the no-argument instance method declared by java.util.Map. Call map.size() to get the number of key–value mappings as an int: 0 for an empty map, or Integer.MAX_VALUE if there are more mappings than an int can represent. If you only need to know whether the map is empty, use map.isEmpty().
Each key present in the map counts as one entry. Two keys with the same value count as two entries. An entry with a null value also counts if the map permits null values. A put that only replaces the value for an existing key adds no entry. Adding a new key does not always increase the entry count: a LinkedHashMap with an eviction policy can remove its eldest entry during the same put, leaving size() unchanged. Size is not capacity: in a HashMap, capacity is the number of buckets, not the number of entries.
For a HashMap that nothing else is changing, map.size() < limit checks whether you can add an entry for a new key without exceeding the limit. A WeakHashMap can shrink without an explicit removal when garbage collection reclaims weakly referenced keys. During concurrent updates to a ConcurrentHashMap, the result may reflect a transient state; checking the size and then calling put does not enforce a limit atomically.
Examples
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
System.out.println(map.size());
map.put(10, "A");
map.put(20, "A");
map.put(30, "B");
System.out.println(map.size());
map.put(30, null);
System.out.println(map.size());
map.put(40, "C");
int limit = 5;
System.out.println(map.size());
boolean hasRoom = map.size() < limit;
System.out.println(hasRoom);
if (hasRoom) {
map.put(95, "D");
}
System.out.println(map.size());
}
}Result
0 3 3 4 true 5
The empty map has size `0`. Keys `10` and `20` share a value, but they still count separately alongside key `30`. Replacing the value for `30` with `null` leaves three entries. Before adding key `95`, the size is `4`, so the comparison with the limit `5` gives `true` and the insertion brings the size to `5`.
Related lessons
- Java · Lesson 17 · Advanced · Version: 2
- Java · Lesson 18 · Advanced · Version: 2
- Java · Lesson 20 · Advanced · Version: 2
- Java · Lesson 42 · Basic · Version: 2
- Java · Lesson 40 · Intermediate · Version: 2