Library contents

Java IntStream.sum

Combine a sequence of whole-unit prices into a single total.

A simple example

IntStream.sum

  1. Start with 1, 2, 3
  2. Do this Start at 0 and add each value
  3. Result 6
The running total changes from 0 to 1, then 3, then 6.

Syntax

Java syntax
prices.stream().mapToInt(Integer::intValue).sum()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Add the prices on a shopping list

A shopper compares the prices in a basket before paying. Work from the prices actually present in the list so a total or minimum reflects the same set of items as the receipt.

Result26
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        var prices = java.util.List.of(8, 3, 12, 3);
        System.out.println(prices.stream().mapToInt(Integer::intValue).sum());
    }
}
Output
26

The four prices add up to 8 + 3 + 12 + 3, giving 26. Both three-unit items count.

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The shift total is the sum of the listed counts. What total goes on the handover slip?

Given6 · 2 · 6 · 0
Worked result14

Review print quantities

A print room records four job quantities, including a cancelled job. The shift total is the sum of the listed counts. What total goes on the handover slip?

Given3 · 0 · 8 · 3
Worked result14

What to watch for

Use integer minor units or decimal arithmetic for prices with fractional currency units.

Documentation for IntStream.sum