A lambda supplies an implementation for an interface with one abstract method. Instead of naming a new class for every small policy, write the policy where it is used. This builds on yesterday's generic types and Day 3's interfaces; lambdas do not replace either idea.
Here an abstract method means a method declared without an implementation, like accepts in Day 3's Rule interface. An interface with one such operation is called a functional interface. Predicate is one supplied by Java; you do not need to define it yourself.
Read minutes -> minutes > 0 as “given minutes, return whether minutes is positive.” The expression after the arrow supplies the result automatically. With several statements, use braces and an explicit return: minutes -> { return minutes > 0; }. The parameter name is yours to choose.
Work through the example
Predicate<Integer> is a library interface whose test method accepts an Integer and returns boolean. The lambda parameter gets its type from that interface. minutes -> minutes > 0 is a compact implementation, not a method being called immediately. Call test to apply it.
A method reference such as Main::positive supplies an existing compatible method as the behavior. The double colon does not execute the method. Use a name when it explains a policy better than a complex inline expression. Short lambdas should still be formatted clearly, with block bodies when several statements are needed.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> shortSession = minutes -> minutes > 0 && minutes <= 25;
Predicate<Integer> positive = Main::positive;
System.out.println(shortSession.test(40));
System.out.println(positive.test(40));
}
static boolean positive(int minutes) {
return minutes > 0;
}
}Check your prediction
false
trueCompare the behavior
A captured local variable must be final or effectively final: assigned once and not reassigned. The lambda can read minimum here because its value stays fixed. This avoids one source of hidden changing policy, but does not freeze any mutable objects captured through a reference. Prefer explicit inputs over mutable captured state.
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
int minimum = 25;
Predicate<Integer> qualifies = value -> value >= minimum;
System.out.println(qualifies.test(25));
System.out.println(qualifies.test(10));
}
}Check your prediction
true
falseSeparate providing behavior from executing it
Assigning a lambda stores behavior compatible with its functional interface. It does not iterate a list or apply itself to every value automatically. In count, the loop decides when to call rule.test(title). The returned boolean then controls whether the count changes.
Trace one title through two rules. For "Go", the length-at-least-four rule returns false, while startsWith("G") returns true. The traversal is the same; only the policy changes. A reusable consumer that accidentally hard-codes one predicate would fail when tested with the other rule.
The lambda's parameter type comes from its target interface. In Predicate<String>, the argument is a String and the result must be boolean. A method reference has to satisfy that same shape. Use an explicit parameter or a named helper when inference or a long expression makes the connection difficult to read.
Practice independently
Lambdas & Method References: practice
Write count(List<String>, Predicate<String>) and use a lambda to count titles of at least four characters. On Read, Go, Test, print 2. Use another lambda with the same method to count titles starting with G, printing 1. Contract: the list, its title elements and the rule are nonnull. title.startsWith("G") is a String method returning true when the text begins with the exact uppercase prefix G.
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
System.out.println("Pass two policies to one counting method");
}
}Hint 1: the idea
The traversal is reusable; only the boolean policy changes.
Hint 2: a first step
Call rule.test(title) in the if condition and increment a count only when it returns true.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
List<String> titles = new ArrayList<>();
titles.add("Read");
titles.add("Go");
titles.add("Test");
System.out.println(count(titles, title -> title.length() >= 4));
System.out.println(count(titles, title -> title.startsWith("G")));
}
static int count(List<String> titles, Predicate<String> rule) {
int count = 0;
for (String title : titles) {
if (rule.test(title)) {
count++;
}
}
return count;
}
}Expected output:
2
1Change it and test again
Use an empty list, an always-false predicate and an always-true predicate. Predict the answers. Then try reassigning a local captured by a lambda and read the compiler error before restoring the code.
Explain before moving on
How does the compiler know a lambda's parameter type? When is a named method reference clearer than an inline lambda?
Completion is saved in this browser only. It does not measure mastery.