Codiqo

Learn Java · lesson 56 of 61 · about 10 minutes

Streams

Process a collection as a pipeline: filter it, change it, and collect or summarise the results.

What you'll learn

  • Build a stream pipeline with filter and map
  • Finish it with collect, count, sum or average
  • Group items with Collectors.groupingBy

The rota in numbers

With the rota in order, the manager wants three numbers from it. First comes a line saying how many hours count as a long shift (8 if it isn't a number). Then the desk prints the hours on the whole rota, Hours on the rota: 24, who works a long shift, Long shifts (6h or more): Cy, Ada, Bo, and the average shift, Average shift: 6.0h. Each one is a short pipeline over the same list of shifts, and the list itself never changes.

A pipeline

A stream passes the items of a collection through steps, like an assembly line:

  • filter(x -> ...) keeps the items that pass a test
  • map(x -> ...) changes each item
  • sorted() puts them in order

A terminal step finishes it: toList() collects a new list, count() counts, and mapToInt(...).sum() adds up numbers. The original list is never changed.

Filter, map, collect

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("ada", "bo", "cy", "dee", "eve");
        List<String> longOnes = names.stream()
            .filter(n -> n.length() == 3)
            .map(String::toUpperCase)
            .toList();
        System.out.println(longOnes);

        List<Integer> scores = List.of(45, 72, 90, 38);
        int total = scores.stream().mapToInt(Integer::intValue).sum();
        long passed = scores.stream().filter(s -> s >= 50).count();
        System.out.println(total + " " + passed);
    }
}

Output

[ADA, DEE, EVE]
245 2

Averages and groups

average() gives an OptionalDouble, because an empty stream has no average: orElse(0) supplies a value for that case. collect(Collectors.groupingBy(...)) builds a Map from a key to the list of items with that key.

Grouping words by first letter

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

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");
        Map<Character, List<String>> byLetter = words.stream()
            .collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.toList()));
        System.out.println(byLetter);

        double avg = words.stream().mapToInt(String::length).average().orElse(0);
        System.out.printf("%.1f%n", avg);
    }
}

Output

{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}
6.6

A lambda can only read what won't change

The filter s -> s.hours() >= longFrom uses a local variable from outside the lambda. Java only allows that when the variable is given a value once and never changed again, called effectively final. So the threshold is worked out in one go, final int longFrom = longLine.matches("[0-9]+") ? Integer.parseInt(longLine) : 8;, instead of being set in one place and changed in another.

Tip

Passing TreeMap::new to groupingBy keeps the keys in sorted order, so the output is the same every time.

Now try it yourself

This lesson is free in Codiqo, with 8 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.