Capstone: a sales report
The functional part ends with the report every business program is: a list of sales, a table of revenue per region, a table of units and revenue per product, a total, and the numbers checked by hand. It uses the record of the value part, the streams of this part and the formatting of lesson 026, and it is the same shape as the word index of lesson 079 with money instead of words.
The model
A sale has a product, a region, a number of units and a price in cents, and its revenue is the product of the last two. The money is a long of cents for the reason of lesson 047: a double cannot hold a cent exactly, and a report that loses a cent per row does not add up.
The record is nested inside the class with the main method, which keeps the file one unit and the checker one program. A record nested in a class is a static nested type, so it is created with new Sale(...) and no outer object.
The report
The region table is one collector: group by the region into a TreeMap, and sum the revenue of each group with summingLong. The total is a second pass, and the table prints the cents through one money method:
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Sales {
record Sale(String product, String region, int units, long cents) {
long revenue() {
return units * cents;
}
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("widget", "north", 10, 1299),
new Sale("widget", "south", 4, 1299),
new Sale("gadget", "north", 2, 4999),
new Sale("gadget", "east", 5, 4999),
new Sale("widget", "east", 7, 1299),
new Sale("gizmo", "south", 3, 250),
new Sale("gizmo", "north", 6, 250));
Map<String, Long> byRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.summingLong(Sale::revenue)));
System.out.printf("%-8s %10s%n", "region", "revenue");
byRegion.forEach((region, cents) -> System.out.printf("%-8s %10s%n", region, money(cents)));
long total = sales.stream().mapToLong(Sale::revenue).sum();
System.out.printf("%-8s %10s%n", "total", money(total));
System.out.println();
Map<String, List<Sale>> byProduct = sales.stream()
.collect(Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.toList()));
System.out.printf("%-8s %6s %10s%n", "product", "units", "revenue");
byProduct.forEach((product, list) -> {
int units = list.stream().mapToInt(Sale::units).sum();
long cents = list.stream().mapToLong(Sale::revenue).sum();
System.out.printf("%-8s %6d %10s%n", product, units, money(cents));
});
System.out.println();
String best = byRegion.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.orElseThrow()
.getKey();
System.out.println("best region: " + best);
System.out.println("largest sale: " + sales.stream()
.max(Comparator.comparingLong(Sale::revenue))
.orElseThrow()
.product());
}
static String money(long cents) {
return String.format("%d.%02d", cents / 100, cents % 100);
}
}
javac -Xlint:all Sales.java
java Sales
region revenue
east 340.88
north 244.88
south 59.46
total 645.22
product units revenue
gadget 7 349.93
gizmo 9 22.50
widget 21 272.79
best region: east
largest sale: gadget
Per product
The product table needs two numbers per group, so the collector keeps the sales themselves and the printing lambda reduces each group. A summingLong downstream could produce the revenue in the same pass, and then the units would need a second collector and the map a second type: for two numbers, the list of sales and two small reductions read better.
The empty line between the tables is System.out.println() with no argument, which prints one line separator. It appears in the output block as the blank line, and the block keeps it because it is part of the run.
The numbers checked
A report is checked by recomputing it another way. The second program states the expected numbers and compares them with the pipeline, so a wrong figure prints FAIL next to the value it measured:
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Checks {
static final List<Sale> SALES = List.of(
new Sale("widget", "north", 10, 1299),
new Sale("widget", "south", 4, 1299),
new Sale("gadget", "north", 2, 4999),
new Sale("gadget", "east", 5, 4999),
new Sale("widget", "east", 7, 1299),
new Sale("gizmo", "south", 3, 250),
new Sale("gizmo", "north", 6, 250));
record Sale(String product, String region, int units, long cents) {
long revenue() {
return units * cents;
}
}
public static void main(String[] args) {
Map<String, Long> byRegion = SALES.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.summingLong(Sale::revenue)));
check("north", 24488, byRegion.get("north"));
check("south", 5946, byRegion.get("south"));
check("east", 34088, byRegion.get("east"));
check("total", 64522, SALES.stream().mapToLong(Sale::revenue).sum());
check("widget units", 21, SALES.stream().filter(s -> s.product().equals("widget")).mapToInt(Sale::units).sum());
check("gadget revenue", 34993,
SALES.stream().filter(s -> s.product().equals("gadget")).mapToLong(Sale::revenue).sum());
long sumOfRegions = byRegion.values().stream().mapToLong(Long::longValue).sum();
check("regions add up", 64522, sumOfRegions);
}
static void check(String name, long expected, long actual) {
System.out.printf("%-16s %s (%d)%n", name, expected == actual ? "ok" : "FAIL", actual);
}
}
javac -Xlint:all Checks.java
java Checks
north ok (24488)
south ok (5946)
east ok (34088)
total ok (64522)
widget units ok (21)
gadget revenue ok (34993)
regions add up ok (64522)
The last check is the one a reader does first: the three region rows must add up to the total. 24488 + 5946 + 34088 is 64522, which is the total row of the first program, and the code checks it rather than trusting the eye.
The same totals with a loop
The third program builds the region totals with a loop and merge, and compares the two maps with equals. Two independent computations that agree are worth more than one that looks right:
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Loop {
record Sale(String product, String region, int units, long cents) {
long revenue() {
return units * cents;
}
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("widget", "north", 10, 1299),
new Sale("widget", "south", 4, 1299),
new Sale("gadget", "north", 2, 4999),
new Sale("gadget", "east", 5, 4999),
new Sale("widget", "east", 7, 1299),
new Sale("gizmo", "south", 3, 250),
new Sale("gizmo", "north", 6, 250));
Map<String, Long> loop = new TreeMap<>();
for (Sale sale : sales) {
loop.merge(sale.region(), sale.revenue(), Long::sum);
}
Map<String, Long> stream = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.summingLong(Sale::revenue)));
System.out.println(loop);
System.out.println(loop.equals(stream));
Map<String, Integer> units = new LinkedHashMap<>();
for (Sale sale : sales) {
units.merge(sale.product(), sale.units(), Integer::sum);
}
System.out.println(units);
}
}
javac -Xlint:all Loop.java
java Loop
{east=34088, north=24488, south=5946}
true
{widget=21, gadget=7, gizmo=9}
The two maps are equal, so the pipeline and the loop agree on all three regions. The second map keeps the order of first appearance because it is a LinkedHashMap, which is why widget comes first there and last in the sorted table of the report.
Exercises
- Add a sale for a product nobody has bought yet and check which tables change.
- Print the revenue of each product as a percentage of the total, with one decimal.
- Sort the product table by revenue instead of by name and print it again.
- Add a check that every region total is the sum of its own sales, computed with a filter.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the sale keep its price in cents?
Answer
A long of cents is exact, while a double cannot hold 0.01 exactly
Money arithmetic must add up, which is why the course has used cents since lesson 047.
-
Which collector builds the region table in one pass?
Answer
groupingBy with summingLong as the downstream collector
The group key is the region and the downstream sums the revenue of each group.
-
Why is the table sorted by region with no sort step?
Answer
The map is a TreeMap, so its keys iterate in order
The map supplier in the three-argument form decides the order of the groups.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Q1 { record Item(String kind, long cents) { } public static void main(String[] args) { List<Item> items = List.of(new Item("a", 100), new Item("b", 200), new Item("a", 50)); Map<String, Long> sums = items.stream() .collect(Collectors.groupingBy(Item::kind, Collectors.summingLong(Item::cents))); System.out.println(sums.get("a")); System.out.println(sums.size()); } }Answer
150 / 2
The two a rows sum to 150, and there are two distinct kinds.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q2 { record Sale(int units, long cents) { long revenue() { return units * cents; } } public static void main(String[] args) { List<Sale> sales = List.of(new Sale(2, 500), new Sale(3, 100)); System.out.println(sales.stream().mapToLong(Sale::revenue).sum()); } }Answer
1300
Two times 500 is 1000 and three times 100 is 300, so the total is 1300 cents.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; public class Q3 { record Sale(String region, long cents) { } public static void main(String[] args) { List<Sale> sales = List.of(new Sale("b", 10), new Sale("a", 20), new Sale("b", 5)); Map<String, Long> sums = sales.stream() .collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.summingLong(Sale::cents))); System.out.println(sums); } }Answer
{a=20, b=15}
The tree orders the keys and the two b rows are summed.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; public class Q4 { record Sale(String product, int units) { } public static void main(String[] args) { List<Sale> sales = List.of(new Sale("x", 2), new Sale("y", 5), new Sale("x", 3)); Map<String, Integer> units = new TreeMap<>(); for (Sale sale : sales) { units.merge(sale.product(), sale.units(), Integer::sum); } System.out.println(units); } }Answer
{x=5, y=5}
The two x rows are summed to five, and the sorted map puts x first.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q5 { record Row(String name, long cents) { } static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); } public static void main(String[] args) { List<Row> rows = List.of(new Row("a", 1299), new Row("b", 50)); System.out.println(rows.stream().map(r -> money(r.cents())).collect(Collectors.joining(", "))); } }Answer
12.99, 0.50
The money method writes the dollars and two digits of cents, and joining separates them.
-
Why does the report print the total from the sales rather than adding the region rows?
Answer
Both should agree, and the check program compares them
Two independent computations are a check on each other, which is what the last check does.
-
Which method turns 1299 cents into 12.99?
Answer
String.format with %d.%02d and the division and remainder by 100
The integer division gives the dollars and the remainder the two digits of cents.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev