When presizing collections from an existing collection or stream, what subtle capacity pitfalls should you watch for?
answer
- new HashMap<>(n) rounds up; threshold is 0.75 of that
- Prefer HashMap.newHashMap(n) on Java 19+
- Two-arg Collectors.toMap grows; pass a map factory
- Capacity rounds up to a power of two
- Capacity is a hint, never a cap on size
basics
~20 sThe classic trap is new HashMap<>(n) with a raw count: n rounds up to a power of two, and for about half of all n the map resizes before n entries fit. Two-argument Collectors.toMap never presizes. HashMap(Map) is safe.
solid answer
~50 sSeveral presizing idioms quietly fail to prevent resizing. Passing new HashMap<>(n) with n as the element count is the classic mistake: the constructor rounds n up to a power of two and the map resizes past 0.75 of that, so new HashMap<>(300) holds 300 entries but new HashMap<>(1000) does not. Two-argument Collectors.toMap starts from a default HashMap and grows as entries arrive; its four-argument overload takes a map factory, so pass () -> HashMap.newHashMap(n). The copy constructor is not a trap: new HashMap<>(otherMap) sizes the table from the source's size and the load factor before inserting. The fix is HashMap.newHashMap(n) (Java 19+), which does the load-factor maths, or on older JDKs Guava's Maps.newHashMapWithExpectedSize(n). ArrayList has no load factor, but new ArrayList<>(collection) has no slack, so the next add grows it. An initial capacity below the data size just means you resize anyway: it's a hint, never a cap.
go deeper
May not be aware of these traps; at minimum should know you can pass a size to the constructor.
Knows to divide the count by the load factor for HashMap and that ArrayList doesn't need it.
Knows the copy constructor is safe, recognizes the stream-collector and putAll pitfalls, reaches for newHashMap, and understands power-of-two rounding and the hint-not-cap semantics.
Codifies safe presizing helpers/conventions, evaluates whether the optimization is worth it via profiling, and is mindful of allocation chunking and GC at scale.
## Why presizing from a source is subtle The goal of presizing is: allocate the backing storage once, big enough that no resize happens while you fill it. But the convenient idioms don't always achieve that, because of the **load factor** and how the JDK chooses capacity. ## Pitfall 1: `new HashMap<>(int)` with the raw element count ```java Map<K,V> m = new HashMap<>(n); // may resize before n entries fit ``` This sets *capacity* to the next power of two >= `n`, and the map resizes once `size > capacity * 0.75`. Whether `n` entries fit depends on where `n` falls: - `new HashMap<>(300)` gets 512 buckets and a threshold of 384, so 300 entries fit. - `new HashMap<>(1000)` gets 1024 buckets and a threshold of 768, so the 769th entry resizes it. For about half of all `n` the raw count falls short. To hold `n` without resizing you need `capacity >= n / 0.75`: ```java Map<K,V> m = new HashMap<>((int)(n / 0.75f) + 1); ``` `new HashMap<>(n, 1.0f)` also avoids the size-triggered resize, because its threshold equals its capacity, but it packs buckets tighter and so raises collisions. ## Not a pitfall: the `HashMap(Map)` copy constructor ```java Map<K,V> copy = new HashMap<>(source); ``` This one is often blamed and is safe. It computes `ceil(source.size() / loadFactor)` and sizes the still-empty table from that before inserting, so with well-spread keys the copy does not resize while it fills: copying 769 entries gives 2048 buckets and a threshold of 1536. (A table under 64 buckets can still resize for a bin past 8 entries: a copy of 12 keys with one hash code ends at 64 buckets.) JDK 8's version computed `size / loadFactor + 1`, which could allocate one size too large but likewise did not resize for size. ## Pitfall 2: `putAll` into a map that already has entries When the target already holds entries, `putAll` grows the table for the source's size alone, not the combined size, so more resizes can happen while it inserts. A default map holding 10 entries (16 buckets) that takes 12 more resizes to 32 buckets partway through. If you know the combined size, presize for that. ## Pitfall 3: stream collectors presize only if you ask ```java Map<K,V> m = items.stream().collect(Collectors.toMap(keyFn, valueFn)); ``` Two-argument `Collectors.toMap`, `toList`, `toSet` and the shorter `groupingBy` overloads start from a default container (`HashMap::new`, `ArrayList::new`, `HashSet::new`) and **grow it dynamically**, whatever size the stream knows. For large, known-size streams this means the usual cascade of resizes. If it matters, pass a factory: - `toMap(km, vm, merge, () -> HashMap.newHashMap(n))` - `groupingBy(classifier, () -> HashMap.newHashMap(n), downstream)` - `Collectors.toCollection(() -> new ArrayList<>(n))` Or skip the collector and loop into a presized container. ## Pitfall 4: power-of-two rounding HashMap capacity is always a power of two. Asking for capacity 1000 yields 1024; asking for 1025 yields 2048. So memory comes in chunks, and tiny differences in your requested capacity can double the allocation. Don't over-think the exact number, but be aware that `+1` in the idiom can occasionally push you over a power-of-two boundary: for 12 entries the idiom asks for 17 and gets 32 buckets, where `HashMap.newHashMap(12)` gets 16. ## Pitfall 5: an `ArrayList` copy has no slack `new ArrayList<>(collection)` needs no load-factor maths, and its capacity equals the source's size, so the first `add` after the copy already grows the array: a copy of 10 elements has capacity 10 and goes to 15. And `new ArrayList<>(0)`, or a copy of an empty collection, skips the default's jump to 10 on first add: it grows 1, 2, 3, 4, 6, 9, copying more often than `new ArrayList<>()`. ## Pitfall 6: capacity is a hint, not a cap Initial capacity never limits how many elements you can add. Undershoot and the collection simply resizes as needed — you lose the optimization but nothing breaks. Overshoot and you waste memory, and a `HashMap` iterates more slowly, since iteration takes time proportional to capacity plus size. So a wrong estimate is normally a performance issue, not a correctness one, though an absurd overshoot can fail outright: `new ArrayList<>(Integer.MAX_VALUE)` throws `OutOfMemoryError`. ## The clean tools - **Java 19+:** `HashMap.newHashMap(n)`, `HashSet.newHashSet(n)`, `LinkedHashMap.newLinkedHashMap(n)`, `LinkedHashSet.newLinkedHashSet(n)` — these take the *expected number of elements* and do the load-factor maths for you. Prefer them. - **Before Java 19:** the `(int)(n / 0.75f) + 1` idiom, or Guava's `Maps.newHashMapWithExpectedSize(n)`, whose map should hold `n` entries without growth; its documentation says that cannot be broadly guaranteed and tells Java 19+ users to prefer `HashMap.newHashMap(n)`. - **ArrayList:** `new ArrayList<>(n)` takes the array length directly (no load factor); `ArrayList.ensureCapacity(n)`, on the class and not on `List`, makes an existing list's capacity at least `n`. ## Summary The recurring theme: don't pass the raw element count as a HashMap *capacity* — account for the 0.75 load factor, prefer `newHashMap`, pass a factory to collectors when the size is known, trust the copy constructor, and treat capacity as a non-binding hint.
- Why is new ArrayList<>(otherList) safe to presize but new HashMap<>(n) often isn't?ArrayList has no load factor: the constructor allocates a backing array exactly the source's size, so the copy itself never resizes, though the next add does. HashMap resizes past 0.75 of its rounded-up capacity, so a raw count may fall short: divide by the load factor or use newHashMap.
- How would you presize a HashMap built via a stream of known size?Two-argument Collectors.toMap can't presize. Use the four-argument overload with a map factory, e.g. collect(Collectors.toMap(k, v, merge, () -> HashMap.newHashMap(n))), or skip the collector and loop the entries into a pre-sized HashMap.newHashMap(n) yourself.
- Believing new HashMap<>(n) guarantees n entries fit without resize
- Assuming Collectors.toMap presizes from the stream's known size — it doesn't
- Treating initial capacity as a maximum size limit
- Forgetting power-of-two rounding when reasoning about memory
- Applying the /0.75 idiom to ArrayList — it has no load factor
- Blaming new HashMap<>(otherMap) for a resize during the copy — it presizes from the source first
- HashMap.newHashMap and sibling factories
- Java 19
Assumes JDK 27; JDK 25 behaves the same here. HashMap.newHashMap and its siblings exist since Java 19, and JDK 8's copy constructor computed size / loadFactor + 1, which could over-allocate but likewise did not resize for size.
context
- HashMap (Java SE 27 & JDK 27)docs.oracle.com
- Collectors (Java SE 27 & JDK 27)docs.oracle.com
- HashMap.java at jdk-27-gagithub.com