Skip to content

Lab: filtering and labeling the catalog

☕ Java 17 · The Ready-Made Lambda Toolkit · 4/4

Goal: split a feature into a filter (Predicate), a formatter (Function) and an output (Consumer), each changeable on its own.

Setup: create CatalogLabelingDemo.java. Run it with java CatalogLabelingDemo.java.

Step 1 — The data

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public class CatalogLabelingDemo {

    record Movie(String title, int min, double rating, boolean kids) { }

    public static void main(String[] args) {
        List<Movie> catalog = List.of(
            new Movie("Dune", 155, 8.0, false),
            new Movie("Coco", 105, 8.4, true),
            new Movie("Enola Holmes", 123, 6.6, true),
            new Movie("Sing", 108, 7.1, true)
        );
    }
}

Step 2 — Four building blocks

Inside main:

        Predicate<Movie> kids = Movie::kids;
        Predicate<Movie> top = m -> m.rating() >= 7;
        Function<Movie, String> label = m -> m.title() + " (" + m.min() + " min)";
        Consumer<String> show = System.out::println;
  • kids is a method reference: kids() returns a boolean.
  • top needs a comparison, so it's a lambda.
  • label turns a Movie into a String.
  • show decides where the text goes.

None of them knows about the others.

Step 3 — Wire them together

        for (Movie m : catalog)
            if (kids.and(top).test(m))
                show.accept(label.apply(m));

For each movie: if it passes kids and top, format it and send it out. Each interface uses its own method: test, apply, accept.

Predict first: Dune isn't for kids, Enola Holmes is rated 6.6. Then run:

$ java CatalogLabelingDemo.java
Coco (105 min)
Sing (108 min)

Step 4 — Change only the output

Replace the Consumer with one that simulates a TV app:

        Consumer<String> show = s -> System.out.println("[TV] " + s);
[TV] Coco (105 min)
[TV] Sing (108 min)

Same filter, same format, a different destination, and one line changed. The Predicate decides what gets through, the Function how it looks, the Consumer where it goes.

Full code on GitHub

← Primitive versions · Back to the series


🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)