Codiqo

Learn Java · lesson 57 of 61 · about 12 minutes

Project: Sales Report

Turn a list of sales into a ranked, grouped summary with streams and comparators.

What you'll learn

  • Model sales with a record
  • Total and group sales with streams
  • Rank results with a comparator

The night's snack sales

Last of all, the manager goes through the night's snack sales by staff member, each typed as a name, a snack and how many, like Ada popcorn 3, until done. Reading them into record SnackSale(String seller, String snack, int qty) is written for you. Your part is the report: how many snacks were sold, Snacks sold: 15, each seller's total with the best first and ties in name order, Ada: 7, and the best-selling snack, Best seller: popcorn (6).

The plan

Each line of input is a sale: Ada tea 3 means Ada sold 3 teas. The report will:

1. Store each sale in a record Sale(String seller, String item, int qty)
2. Work out the total quantity sold
3. Total each seller's sales with groupingBy and summingInt
4. Rank the sellers, best first, with ties in name order

Totals per seller

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    record Sale(String seller, String item, int qty) {}

    public static void main(String[] args) {
        List<Sale> sales = List.of(
            new Sale("Ada", "tea", 3), new Sale("Bo", "cake", 5), new Sale("Ada", "cake", 4));
        int total = sales.stream().mapToInt(Sale::qty).sum();
        Map<String, Integer> bySeller = sales.stream()
            .collect(Collectors.groupingBy(Sale::seller, TreeMap::new, Collectors.summingInt(Sale::qty)));
        System.out.println(total + " " + bySeller);
    }
}

Output

12 {Ada=7, Bo=5}

Ranking the map

A Map has no order of its own to sort, but its entrySet() can be streamed. Map.Entry.comparingByValue() compares entries by their values; reverse it for biggest first, and break ties with comparingByKey().

Best seller first

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> bySeller = Map.of("Ada", 7, "Bo", 5, "Cy", 7);
        bySeller.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
                .thenComparing(Map.Entry.comparingByKey()))
            .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
    }
}

Output

Ada: 7
Cy: 7
Bo: 5

The best seller, and a tie

For the best snack, group by snack instead of by seller, into a TreeMap so the snacks are in name order, then max(Map.Entry.comparingByValue()) picks the entry with the biggest total and map(Map.Entry::getKey) keeps its name. When two snacks sell the same number, max keeps the first one it met, so the TreeMap's order means the earlier name wins.

Tip

Map.of makes a map with no fixed order. Sorting its entries, or using a TreeMap, is how you get output that's the same every time.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.