Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A service computing totals with list.stream().map(Order::amount).reduce(0, Integer::sum) shows high allocation in a profiler and sometimes an incorrect total for large values. What is wrong?

map(Order::amount) turns every int amount into an Integer object, and reduce(0, Integer::sum) unboxes and re-boxes the running total at every step, so a hot path allocates objects per element, which is what the profiler shows. The incorrect totals come from int overflow: once the sum passes 2,147,483,647 it silently wraps to a negative number. The fix is mapToLong(Order::amount).sum(), or Math.addExact when an overflow must fail loudly, and for money a long count of minor units such as cents, or BigDecimal, rather than int.

Why this question is asked

This question combines two problems that often travel together in older code: a performance problem that only shows up in a profiler, and a correctness problem that only shows up with large numbers. Both come from the same line, and both are fixed by understanding what types the stream really works with. Interviewers like it because it tests boxing, primitive streams and integer arithmetic at once, and because the money angle reveals whether we think about domain types. In this answer, we will recap boxing and int limits, take the line apart to see where the allocations come from, reproduce the wrong total, fix both problems, and choose the right type for money.

1A Quick Recap: Boxing and the Range of int

Java's primitive int holds a 32-bit value directly. Integer is an object that wraps an int. Generic types such as Stream<T> can only hold objects, so a Stream of numbers made with map is a Stream<Integer>, and every int put into it is boxed, wrapped into an Integer, usually through Integer.valueOf. Values from -128 to 127 come from a cache; anything else is a new object of about 16 bytes.

An int can hold values from -2,147,483,648 to 2,147,483,647. When an addition goes past the maximum, Java does not throw an error. The value wraps around, continuing from the most negative number, which is called overflow. long, a 64-bit type, goes up to about 9.2 quintillion.

2Where the Allocations Come From

Let us look at what the original line does for each order.

Java
record Order(String id, int amount) {} // amount in cents
int total = list.stream()
.map(Order::amount) // int -> Integer.valueOf(amount): boxing
.reduce(0, Integer::sum); // unbox total and element, add, box the new total
Step throughWhat happens to each amount in the original line
  1. Order.amount() returns an intfor example 125000
  2. map boxes itInteger.valueOf(125000): a new object
  3. reduce unboxes total and elementtwo int values
  4. Adds them as intwraps silently past 2,147,483,647
  5. Boxes the new totalanother new Integer for the next step

5 steps in order. Play them, or step through them one at a time.

Two allocations per element, and an int addition that can overflow.

For each order, map boxes the amount into an Integer, because the result of map must be an object in a Stream<Integer>. Then reduce, which works on Integers, unboxes the running total and the element, adds them as ints, and boxes the result again to pass it on as the new running total. Amounts in cents are almost never between -128 and 127, so most of these are real allocations: roughly two short-lived objects per order.

The JIT compiler can sometimes remove such allocations, but across a stream pipeline it often cannot. In a hot path processing millions of orders per minute, these objects are what the allocation profiler shows, coming from Integer.valueOf, and they keep the garbage collector busy for no business reason.

3Reproducing the Wrong Total

The second symptom is a total that is sometimes wrong for large values. Three large orders are enough to see it.

Java
List<Order> list = List.of(
new Order("a", 1_000_000_000), // 10,000,000.00 in cents
new Order("b", 1_000_000_000),
new Order("c", 1_000_000_000));
int total = list.stream().map(Order::amount).reduce(0, Integer::sum);
System.out.println(total); // -1294967296

The true total is 3,000,000,000 cents, but an int cannot hold it. After passing 2,147,483,647, the sum wraps around and ends at 3,000,000,000 - 4,294,967,296 = -1,294,967,296. Nothing throws, nothing logs, and in a report a negative total may simply look like a large refund. Smaller overflows are worse: a sum that wraps twice can land on a positive, plausible-looking number.

4The Fix: mapToLong and sum

Both problems are fixed by switching to a primitive stream with a wider type.

Java
long total = list.stream()
.mapToLong(Order::amount) // int widened to long, no boxing
.sum(); // 3000000000
long checked = list.stream()
.mapToLong(Order::amount)
.reduce(0L, Math::addExact); // throws ArithmeticException if a long overflows
int strict = list.stream()
.mapToInt(Order::amount)
.reduce(0, Math::addExact); // ArithmeticException: integer overflow

mapToLong produces a LongStream, which holds raw long values, so there is no boxing at all, and the method reference Order::amount works even though it returns an int, because int widens to long automatically. sum on a LongStream adds longs, which will not overflow for any realistic sum of int amounts.

Math.addExact is the right tool when an overflow must never pass silently. It adds two numbers and throws ArithmeticException if the result does not fit. The last example keeps int but uses addExact, so the bad total becomes a loud failure instead of a wrong number. In most money code, a loud failure is far better than a quietly wrong report.

5Choosing the Right Type for Money

The deeper fix is the type of amount itself. An int of cents can only represent up to about 21.4 million in currency units, which a single day's revenue of a mid-sized business can exceed. A long of minor units, cents or the smallest unit of the currency, goes up to about 92 quadrillion cents, which is enough for any total, and adds exactly and quickly. BigDecimal is the other standard choice: it represents decimal values exactly, handles any size and supports explicit rounding modes, at the cost of being an object and slower.

Java
record Order(String id, long amountMinor, Currency currency) {} // long minor units
long totalMinor = orders.stream().mapToLong(Order::amountMinor).sum();
record Invoice(String id, BigDecimal amount) {} // or BigDecimal
BigDecimal total = invoices.stream().map(Invoice::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
Summing order amounts
ApproachBoxingOverflow behaviourFit for money
map(...).reduce(0, Integer::sum)two objects per elementwraps silently at 2.1 billionno
mapToInt(...).sum()nonewraps silently at 2.1 billionno
mapToLong(...).sum()nonefine for int amountsyes, as minor units
mapToLong(...).reduce(0L, Math::addExact)nonethrows on overflowyes
reduce(BigDecimal.ZERO, BigDecimal::add)objects by designnever overflowsyes, exact decimals
Primitive long streams fix both the allocation and the overflow.

Which one to pick depends on the domain. Long minor units suit high-volume systems such as payments and ledgers, where every operation is an addition of whole cents. BigDecimal suits calculations with fractional results, such as interest, tax or currency conversion, where we need explicit rounding. What we never use is double, which cannot represent most decimal amounts exactly. And whichever type we choose, amounts in different currencies must never be summed together, so a real model keeps the currency next to the amount.

6Follow-up questions

Why does the method reference Order::amount work with mapToLong if it returns int?

mapToLong expects a ToLongFunction, whose method returns long. A method reference whose method returns int is compatible because int converts to long by widening, a conversion Java applies automatically and without loss. The compiler inserts the conversion for us.

Would Collectors.summingInt fix the boxing?

Partly. summingInt accumulates into an int internally, so it avoids reboxing the running total, but the stream before it is usually already a Stream<Order>, and its result is boxed once. It still overflows like int. mapToLong(...).sum() is simpler and fixes both problems.

How would you confirm the fix in the profiler?

Run the same load before and after and compare the allocation profile, for example with Java Flight Recorder or async-profiler in allocation mode. The allocations from Integer.valueOf in this code path should disappear, and garbage collection frequency for that workload should drop.

7Conclusion

In this answer, we saw that map(Order::amount).reduce(0, Integer::sum) boxes every amount and re-boxes the running total at each step, creating garbage in a hot path, and that int addition overflows silently past 2,147,483,647, turning three ten-million orders into a negative total. mapToLong(Order::amount).sum() removes the boxing and the overflow, Math.addExact makes any overflow fail loudly, and for money the amount should be a long of minor units or a BigDecimal, kept together with its currency.

What to say in the interviewAbout 90 seconds aloud

Open with

There are two problems in that one line. First, map(Order::amount) produces a Stream<Integer>, so every int amount is boxed with Integer.valueOf, and amounts in cents are almost never in the small cached range, so that is a new object per order.

Then, if they want more

Then reduce with Integer::sum unboxes the running total and the element, adds them and boxes the result again, so it is roughly two allocations per element. In a hot path that is exactly the Integer allocation the profiler shows.

Second, the sum is an int, and int overflows silently: once the total passes about 2.1 billion it wraps to a negative number. Three orders of a billion cents each come out as minus 1,294,967,296, with no exception.

The fix is list.stream().mapToLong(Order::amount).sum(). mapToLong gives a LongStream of raw values, so there is no boxing, and int widens to long automatically, so the method reference still works; a long sum will not overflow for int amounts. If an overflow must never pass silently, I would use reduce with Math::addExact, which throws ArithmeticException.

And I would question the model: money should not be an int. I would use a long count of minor units like cents for high-volume additions, or BigDecimal when we need exact decimal arithmetic with rounding, and always keep the currency with the amount.

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.
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 service computing totals with list.stream().map(Order::amount).reduce(0, Integer::sum)...": https://scrivio-interview-library.netlify.app/java/streams/6d3787a6f3/