Quick revision
The short answer
Integer.valueOf in a profile means the hot path is boxing ints into Integer objects, here because of Map<Integer, Integer> and Stream<Integer>. I would first confirm the boxing call sites with an allocation profiler, then switch streams to IntStream, replace the boxed map with a primitive collection or a plain array when the keys are dense, and measure the change with JMH. Because those changes add dependencies or make code less idiomatic, I would apply them only on paths the profile proves are hot.
What to remember
In this answer, we saw that Integer.valueOf in a profile points at boxing in generic code, here a Map<Integer, Integer> and a Stream<Integer>. We confirmed the call sites with async-profiler or JFR allocation events, switched streams to IntStream with mapToInt and sum, replaced boxed maps with arrays for dense keys or a primitive collection for sparse ones, weighed the extra dependency and less idiomatic code against the GC savings, and proved the result with JMH using -prof gc.
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.
Integer.valueOf in a profile means the hot path is boxing ints into Integer objects, here because of Map<Integer, Integer> and Stream<Integer>. I would first confirm the boxing call sites with an allocation profiler, then switch streams to IntStream, replace the boxed map with a primitive collection or a plain array when the keys are dense, and measure the change with JMH. Because those changes add dependencies or make code less idiomatic, I would apply them only on paths the profile proves are hot.
Why this question is asked
Performance work in Java services often comes down to allocation rather than raw computation. A high allocation rate makes the garbage collector run more often, uses CPU and memory bandwidth, and adds latency at the tail. Boxing is one of the most common sources, because it hides inside ordinary generic code. Interviewers ask this scenario to see whether we measure before we change things, whether we know the primitive alternatives, and whether we can weigh their costs honestly. In this answer, we will recap why generic code boxes, confirm the cause with a profiler, look at the fix for streams and for maps, discuss the trade-offs, and finish with how to prove the gain.
1A Quick Recap: Why Generic Code Boxes
Java generics only accept object types, so a Map<Integer, Integer> stores Integer objects for both keys and values, and a Stream<Integer> passes Integer objects between its stages. Each time an int enters such a structure, the compiler inserts Integer.valueOf, which returns a cached object for -128 to 127 and allocates a new 16-byte Integer for everything else. Each time we read a value back as an int, it calls intValue(). So a loop that does map.put(id, map.get(id) + 1) unboxes once and boxes once on every iteration, and for ids above 127 it boxes the key as well.
2Confirming Where the Boxing Happens
A CPU profile that shows Integer.valueOf tells us that boxing is happening, but not which code does it, and not how much memory it costs. An allocation profile answers both. async-profiler in allocation mode or Java Flight Recorder's allocation sampling events record stack traces at allocation sites, so we can see which of our methods creates the Integers.
- Allocation profilewhich call sites create Integer objects?
- Is it a significant share of allocation on a hot path?YesPlan a primitive alternativeNoLeave the idiomatic code alone
- Change one call site
IntStream, primitive map or array - Re-measure with JMH and in the serviceallocation rate, GC time, latency
4 steps in order. Play them, or step through them one at a time.
In the flame graph we look for java.lang.Integer under our own frames. A typical finding is one or two methods responsible for most of the Integer allocations, for example a scoring method that sums a Stream<Integer> and a counter that updates a Map<Integer, Integer>. Those are the only places worth changing.
3Streams: Stay Primitive From Start to End
Stream<Integer> with reduce boxes every intermediate result. IntStream works on ints directly and has sum, average, min and max built in. mapToInt converts once from objects to ints, and from then on nothing is boxed.
The rule of thumb is to switch to the primitive stream as early as possible and avoid boxed() unless an API really needs objects. If Order::quantity itself returns Integer, mapToInt still has to unbox each value, so it is worth checking the source types too.
4Maps Keyed by int: Primitive Collections or Arrays
For maps, the JDK has no primitive version, so we have two options. When the keys are dense, meaning they fall in a known small range such as 0 to 10,000, a plain int[] indexed by the key is the fastest and smallest map possible. When the keys are sparse, a primitive collection library such as fastutil, Eclipse Collections or HPPC provides hash maps that store keys and values in int arrays, with no objects per entry.
A boxed HashMap<Integer, Integer> entry costs a node object, a key Integer and a value Integer, roughly 60 to 70 bytes per entry on a typical JVM, while an open-addressing primitive map needs around 8 bytes per slot plus spare capacity. That difference shows up both in heap size and in allocation rate.
5Weighing the Trade-offs
These changes are not free. A primitive collection library is another dependency to keep updated and to audit, and its primitive methods are not part of the java.util interfaces, so code that passes these maps around as a plain Map quietly falls back to boxed methods. Arrays need us to manage bounds and growth. IntStream code is a little less general than Stream<Integer>. New team members also need to understand why the code looks different from the rest of the service.
So the decision is a trade between throughput, GC savings and latency on one side, and simplicity and consistency on the other. I would make it per call site, only where the allocation profile shows a large share, and leave a short comment saying why. A path that runs a thousand times per request deserves it; a path that runs once at startup does not.
6Proving the Gain With JMH
After the change, we measure again. In the service, we compare the allocation rate and GC time from the same profiler. In isolation, we write a JMH benchmark, because a hand-written timing loop is easily fooled by JIT warm-up and by dead-code elimination, where the compiler removes work whose result is never used. JMH handles warm-up and forking, and it gives us tools to keep results alive.
Returning the result from each benchmark method lets JMH consume it, so the JIT cannot discard the computation. The -prof gc option reports bytes allocated per operation, which is the number we were trying to reduce in the first place.
7Follow-up questions
How would you write a JMH benchmark that avoids dead-code elimination?
Every result must be used, either by returning it from the @Benchmark method or by passing it to a Blackhole with blackhole.consume(value). Inputs should come from @State fields set up in @Setup, not from constants, otherwise the JIT can fold the whole computation into a constant. I would also let JMH handle warm-up iterations and forks, and run with -prof gc to see allocation per operation alongside the time.
Could the JIT remove the boxing on its own?
Escape analysis can remove some boxing when the Integer never leaves a compiled, inlined method, but it rarely helps with values stored in a HashMap or passed through a stream pipeline, because those objects escape. So for maps and streams we should not count on it.
8Conclusion
In this answer, we saw that Integer.valueOf in a profile points at boxing in generic code, here a Map<Integer, Integer> and a Stream<Integer>. We confirmed the call sites with async-profiler or JFR allocation events, switched streams to IntStream with mapToInt and sum, replaced boxed maps with arrays for dense keys or a primitive collection for sparse ones, weighed the extra dependency and less idiomatic code against the GC savings, and proved the result with JMH using -prof gc.
Open with
First I would confirm what the profiler is hinting at. Integer.valueOf is boxing, but I want the call sites and the allocation volume, so I would take an allocation profile with async-profiler in alloc mode or JFR allocation events and find which of our methods create the Integer objects.
Then, if they want more
Usually it is a few places. For streams, the fix is to stay primitive: mapToInt as early as possible and then sum or other IntStream operations, instead of Stream<Integer> with reduce, which unboxes and reboxes at every step.
For the Map<Integer, Integer>, if the key space is dense, say ids from zero to ten thousand, a plain int array indexed by key is the smallest and fastest option. If the keys are sparse, a primitive collection library like fastutil or Eclipse Collections stores keys and values in int arrays with no per-entry objects.
The trade-off is an extra dependency, types that do not implement the standard interfaces, and code that looks different from the rest, so I would only do it on the paths the profile proves are hot and leave a comment explaining why.
Then I would measure again: a JMH benchmark with -prof gc to see bytes per operation, making sure results are returned or consumed by a Blackhole so dead-code elimination does not fake the result, and the allocation rate and GC time in the real service.
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 Java Language Specification, Java SE 21, Java SE 21 API 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 "A profiler shows that a hot path spends significant time in Integer.valueOf and the...": https://scrivio-interview-library.netlify.app/java/types-and-values/d5db07c5ea/