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;
kidsis a method reference:kids()returns aboolean.topneeds a comparison, so it's a lambda.labelturns aMovieinto aString.showdecides where the text goes.
None of them knows about the others.
Step 3 — Wire them together¶
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:
Step 4 — Change only the output¶
Replace the Consumer with one that simulates a TV app:
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.
← Primitive versions · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)