Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Collections and the Stream API

By the end of this chapter, you'll be able to

  • Choose between List, Set, Map and Deque depending on the operations
  • Transform a collection with filter, map, sorted and toList
  • Group and aggregate with Collectors.groupingBy
  • Remove elements from a list without a ConcurrentModificationException

The essential collections

void main() {
    Set<String> cities = new TreeSet<>(List.of("Lomé", "Accra", "Lomé", "Cotonou"));
    IO.println(cities + " " + cities.contains("Accra"));

    Deque<String> stack = new ArrayDeque<>();
    stack.push("page 1");
    stack.push("page 2");
    IO.println("back to: " + stack.pop() + ", then " + stack.peek());

    Map<String, List<String>> enrolled = new TreeMap<>();
    enrolled.computeIfAbsent("python", k -> new ArrayList<>()).add("Awa");
    enrolled.computeIfAbsent("java", k -> new ArrayList<>()).add("Bilal");
    enrolled.computeIfAbsent("python", k -> new ArrayList<>()).add("Chloé");
    IO.println(enrolled);
}
[Accra, Cotonou, Lomé] true
back to: page 2, then page 1
{java=[Bilal], python=[Awa, Chloé]}
NeedInterfaceCommon implementation
an ordered sequence, with duplicatesListArrayList
unique elementsSetHashSet, or TreeSet for sorted order
a key associated with a valueMapHashMap, or TreeMap for sorted order
a stack or a queueDequeArrayDeque

Declare the variable with the interface (Set<String>) and choose the implementation at new: you can change it without touching the rest. computeIfAbsent creates a key's list the first time it is used.

The Stream API

A stream is a flow of elements on which you chain operations. Intermediate operations (filter, map, sorted…) describe the processing; a terminal operation (toList, count, collect…) triggers it.

record Student(String name, String group, double average) {}

void main() {
    List<Student> students = List.of(
        new Student("Awa", "3A", 15.5), new Student("Bilal", "3B", 11.0), new Student("Chloé", "3A", 9.0),
        new Student("Diego", "3B", 16.5), new Student("Emeka", "3A", 12.0));

    List<String> passed = students.stream()
        .filter(s -> s.average() >= 12)
        .map(Student::name)
        .sorted()
        .toList();
    IO.println("Passed: " + passed);

    double best = students.stream().mapToDouble(Student::average).max().orElse(0);
    IO.println("Best average: " + best);

    Map<String, Long> perGroup = students.stream()
        .collect(Collectors.groupingBy(Student::group, TreeMap::new, Collectors.counting()));
    IO.println("Headcount: " + perGroup);

    Map<String, Double> averagePerGroup = students.stream()
        .collect(Collectors.groupingBy(Student::group, TreeMap::new, Collectors.averagingDouble(Student::average)));
    averagePerGroup.forEach((group, avg) -> IO.println(group + ": " + String.format("%.2f", avg)));

    String names = students.stream().map(Student::name).collect(Collectors.joining(", ", "[", "]"));
    IO.println(names);
}
Passed: [Awa, Diego, Emeka]
Best average: 16.5
Headcount: {3A=3, 3B=2}
3A: 12.17
3B: 13.75
[Awa, Bilal, Chloé, Diego, Emeka]
  • Student::name is a method reference, a shortcut for s -> s.name().
  • mapToDouble produces a stream of double, which offers max(), sum(), average(). max() returns an OptionalDouble, empty if the stream is: orElse(0) gives a default value.
  • Collectors.groupingBy(key, TreeMap::new, aggregation) groups by key into a (sorted) TreeMap and aggregates each group: counting(), averagingDouble(…), summingDouble(…), toList()…
  • String.format("%.2f", avg) follows the conventions of the computer's language: here 12.17 with a decimal point; on a French system it would print 12,17.
  • A stream can be traversed only once, and never modifies the original collection.

toList triggers the whole processing and produces an unmodifiable list.

Step 5 of 5
Text description of the animation
  1. The stream goes through the list, without copying or modifying it.
  2. filter keeps averages of at least 12: Bilal and Chloé are left out.
  3. map turns each student into their name.
  4. sorted sorts the names.
  5. toList triggers the whole processing and produces an unmodifiable list.

Your turn

Worked exercise

Solved exercise: the shop's sales

From a list of sales record Sale(String seller, String product, int quantity, double unitPrice), display: the revenue per seller in a TreeMap, the name of the best seller, and the sorted list of products sold, without duplicates.

Hint 1
Add a method double amount() to the record, then use Collectors.summingDouble(Sale::amount) in a groupingBy.
Hint 2
The best seller: perSeller.entrySet().stream().max(Map.Entry.comparingByValue()). For the products: map, distinct, sorted, toList.
Show the solution and common mistakes
record Sale(String seller, String product, int quantity, double unitPrice) {
    double amount() { return quantity * unitPrice; }
}

void main() {
    List<Sale> sales = List.of(
        new Sale("Kofi", "wax print", 3, 12.0), new Sale("Lena", "bag", 1, 25.0),
        new Sale("Kofi", "bracelet", 5, 4.0), new Sale("Lena", "wax print", 2, 12.0),
        new Sale("Mo", "bag", 2, 25.0));

    Map<String, Double> perSeller = sales.stream()
        .collect(Collectors.groupingBy(Sale::seller, TreeMap::new, Collectors.summingDouble(Sale::amount)));
    IO.println(perSeller);

    String best = perSeller.entrySet().stream()
        .max(Map.Entry.comparingByValue())
        .map(Map.Entry::getKey)
        .orElse("nobody");
    IO.println("Best seller: " + best);

    List<String> products = sales.stream().map(Sale::product).distinct().sorted().toList();
    IO.println(products);
}
{Kofi=56.0, Lena=49.0, Mo=50.0}
Best seller: Kofi
[bag, bracelet, wax print]

Common mistakes:

  • Using a HashMap for display: the totals are right, but the order of the sellers isn't guaranteed.
  • Calling .get() on the result of max without checking: with an empty list, Optional.get() throws a NoSuchElementException. orElse handles that case.

Summary

  1. 1List, Set, Map and Deque meet different needs; declare with the interface.
  2. 2A stream chains intermediate operations and is triggered by a terminal operation.
  3. 3filter keeps, map transforms, sorted sorts, toList or collect produce the result.
  4. 4Collectors.groupingBy groups and aggregates in a single operation.
  5. 5To remove during a walk, use removeIf rather than a for-each loop.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.