Quick revision
The short answer
I would set ownership rules so that each collection is made unmodifiable once, at the boundary where it is created, with List.copyOf or Stream.toList, and callers then trust it instead of copying it again. On top of that, the team picks the right type from the start, such as a Set when contains is the main operation, avoids intermediate collections in streams, and relies on List.copyOf returning the same instance when its argument is already one of the JDK's immutable lists. Every change is guided by allocation profiling with JFR or async-profiler, before and after, fixing the hot paths first rather than the whole codebase.
What to remember
In this answer, we saw that excessive collection conversions come from unclear ownership, so each layer copies to protect itself. We fixed it with rules: make a collection unmodifiable once at the boundary and trust it afterwards, store data in the type it is used as, chain stream operations instead of collecting in between, and rely on List.copyOf returning the same instance for lists that are already immutable. Allocation profiling with JFR or async-profiler before and after keeps the effort on the hot paths that matter.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would set ownership rules so that each collection is made unmodifiable once, at the boundary where it is created, with List.copyOf or Stream.toList, and callers then trust it instead of copying it again. On top of that, the team picks the right type from the start, such as a Set when contains is the main operation, avoids intermediate collections in streams, and relies on List.copyOf returning the same instance when its argument is already one of the JDK's immutable lists. Every change is guided by allocation profiling with JFR or async-profiler, before and after, fixing the hot paths first rather than the whole codebase.
Why this question is asked
Allocation is not free even with a modern garbage collector. Every short-lived list costs time to create and fill, and a high allocation rate means more frequent young collections, more CPU spent on GC and worse tail latency. When a profile shows that a fifth of all allocation is collections being turned into other collections, the service is spending real money moving the same references around. Interviewers ask this to see whether we can cut that waste without giving up the safety that defensive copies provide. In this answer, we will see where the copies come from, set ownership rules, choose types up front, clean up streams, use cheap immutable copies, and measure the result.
1Where the Copies Come From
Each copy in such a profile usually has a good reason behind it. A developer converted a list to a set because a contains check on a list is slow. Another collected a stream to a list and copied it into an ArrayList because they were not sure the result could be modified. A third copied every collection received from another layer because they did not know whether the caller might change it later. Each layer protects itself, and together they copy the same data four or five times per request.
So the root problem is not that developers are careless; it is that nobody knows who owns a collection and whether it can change. Once that is clear, most copies become unnecessary. That is why the first fix is a rule, not a code change.
- Repository returns a Listnew
ArrayListfrom the query result - Service copies itnew
ArrayList(list), in case it changes - Service builds a Set for lookupsnew
HashSet(list), on every call - Mapper streams and collectscollect to List, then new
ArrayListagain - Controller copies for safety
List.copyOf(list)before returning
5 steps in order. Play them, or step through them one at a time.
Five allocations of the same references; each layer protects itself because ownership is unclear.
2Rule 1: Make It Immutable Once, Then Trust It
The ownership rule I would set is simple. Whoever creates a collection that leaves its method makes it unmodifiable at that point, with List.copyOf, Set.copyOf or Stream.toList. Everyone who receives a collection from inside our codebase can then rely on it not changing, so they do not copy it again. A returned collection is a value, not shared mutable state.
Notice that the safety has not gone away. Nobody can modify the results, because they are unmodifiable; we just no longer pay for extra protection against something that cannot happen. The rule needs to be written down and checked in code review, because it only works if the creators keep their side of it.
3Rule 2: Choose the Right Type From the Start
A common source of conversions is a collection built as one type and used as another. If a method receives a list of allowed IDs and the main operation is contains, it often converts the list to a HashSet on every call. Converting a 10,000-element list on every request allocates a hash table and 10,000 nodes each time.
The principle is to store data in the shape in which it is used. If both list order and fast lookup are needed, keep both, a list and a set, built once together, rather than converting on demand.
4Rule 3: Avoid Intermediate Collections in Streams
Streams invite a pattern where every step is collected to a list and the next step streams it again. Each collect allocates a new list, though the stream could have passed elements straight through. Chaining the operations and collecting once at the end removes those lists. Where the logic is complex, a plain loop that builds one result is often both clearer and cheaper.
5Rule 4: Cheap Copies When the Source Is Already Immutable
Sometimes a defensive copy is still written, for example in a constructor that must not trust its caller. Here the JDK helps. List.copyOf checks whether its argument is already one of the JDK's own immutable lists, such as one made by List.of or an earlier List.copyOf, and if so returns the same instance without copying. Set.copyOf and Map.copyOf do the same for their types. So when the ownership rule is followed, a defensive List.copyOf on an already immutable list costs almost nothing.
Notice the second case. Stream.toList returns an unmodifiable list, but unlike List.of it allows nulls, and in current JDKs List.copyOf copies it rather than return it, because copyOf must reject nulls. So in code where both are common, it is better to standardise on one way of making results immutable at each boundary, so the copies collapse as intended.
6Measure First, Fix the Hot Paths
None of this should be done blindly across the whole codebase. I would start with an allocation profile, from Java Flight Recorder's allocation events or async-profiler in allocation mode, recorded under realistic load. The profile shows which call sites allocate the most, and usually a handful of hot paths account for most of the 20 percent. We fix those first, one at a time, and re-run the profile after each change to confirm the drop.
A realistic target is to bring that 20 percent down to a few percent by fixing perhaps ten call sites, with a visible fall in GC frequency and some improvement in tail latency. The rest of the codebase adopts the ownership rule gradually, as code is touched.
7Follow-up questions
When is a defensive copy still required?
When we store a collection we did not create and cannot trust, for example one passed in by a caller outside our module or by a library, because the caller could change it later and corrupt our state. Also when we return our internal mutable state, or when data crosses a trust boundary such as a public API. In those cases we copy, ideally with List.copyOf, which is free if the input is already immutable.
Is allocation of short-lived objects really expensive with modern collectors?
Each allocation is cheap, a pointer bump in a thread-local buffer, and short-lived objects die young, which generational collectors handle well. But at high rates the young collections become frequent and add CPU time and pauses. A fifth of all allocation is enough to matter, which is why the profile should decide.
8Conclusion
In this answer, we saw that excessive collection conversions come from unclear ownership, so each layer copies to protect itself. We fixed it with rules: make a collection unmodifiable once at the boundary and trust it afterwards, store data in the type it is used as, chain stream operations instead of collecting in between, and rely on List.copyOf returning the same instance for lists that are already immutable. Allocation profiling with JFR or async-profiler before and after keeps the effort on the hot paths that matter.
Open with
I would start by explaining why the copies exist: each layer copies because nobody knows who owns a collection or whether it can change. So the first fix is an ownership rule.
Then, if they want more
Whoever creates a collection that leaves a method makes it unmodifiable once, with List.copyOf or Stream.toList, and every caller inside our codebase trusts it and does not copy again. The safety stays, because the result really cannot be changed. Second, choose the right type from the start.
If the main operation is contains, keep a Set, built once, instead of converting a list on every call. Third, in streams, chain the operations and collect once at the end, or use a plain loop when that is clearer, instead of collecting to a list after every step.
Fourth, where a defensive copy is still needed, List.copyOf returns the same instance if the input is already a List.of style immutable list, so it is nearly free; I would note that Stream.toList results are copied in current JDKs because they allow nulls, so it helps to standardise on one way at each boundary.
Defensive copies are still required for collections from untrusted callers that we store. And I would not refactor everything. I would profile allocation with JFR or async-profiler under realistic load, fix the top call sites first, re-measure after each change, and let the rest adopt the rules as code is touched.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Profiling a high-traffic service shows that 20 percent of allocation comes from...": https://scrivio-interview-library.netlify.app/java/collections-overview/161e66bdb5/