Lab: building the rows of the home screen¶
☕ Java 17 · Passing Behavior Around with Lambdas · 3/3
Goal: power every row of a streaming home screen with one method, where each row's rule is a one-line lambda.
Setup: in an empty folder, create Movie.java, MovieFilter.java and HomeScreen.java. No package.
Step 1 — The data and the rule¶
One abstract method, Movie in, boolean out: any lambda of that shape can stand in for it. @FunctionalInterface asks the compiler to guarantee there's exactly one abstract method.
Step 2 — One method for every row¶
import java.util.List;
public class HomeScreen {
static void showRow(String name, List<Movie> catalog, MovieFilter rule) {
System.out.println("=== " + name + " ===");
for (Movie m : catalog) {
if (rule.test(m)) {
System.out.println(" > " + m.title() + " (" + m.minutes() + " min)");
}
}
System.out.println();
}
}
showRow() doesn't know what the rule is. It just asks it about each movie.
Step 3 — A catalog and three rows¶
public static void main(String[] args) {
List<Movie> catalog = List.of(
new Movie("Midnight Signal", true, false, 118),
new Movie("The Lantern Fox", true, true, 95),
new Movie("Empire of Sand", false, false, 172),
new Movie("Ocean Pals", false, true, 88),
new Movie("The Long Winter", true, false, 158)
);
showRow("New This Week", catalog, m -> m.isNew());
showRow("Family Night", catalog, m -> m.isKidFriendly());
showRow("Epic Watches", catalog, m -> m.minutes() > 150);
}
No type is written for m: the MovieFilter parameter tells the compiler it's a Movie, so your editor even autocompletes m..
Step 4 — A new row in one line¶
The product team wants short movies, under 100 minutes:
No new class, no change to showRow() or Movie.
Step 5 — Run¶
$ javac *.java
$ java HomeScreen
=== New This Week ===
> Midnight Signal (118 min)
> The Lantern Fox (95 min)
> The Long Winter (158 min)
=== Family Night ===
> The Lantern Fox (95 min)
> Ocean Pals (88 min)
=== Epic Watches ===
> Empire of Sand (172 min)
> The Long Winter (158 min)
=== Quick Bites ===
> The Lantern Fox (95 min)
> Ocean Pals (88 min)
The Lantern Fox appears in three rows: same movie, same catalog, same method, different rule each time.
← Lambda syntax · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)