java · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
has a lambda type for most jobs.
Writing a new interface for every lambda gets tiring, so Java ships a set in java.util.function. A Function<T, R> turns a T into an R with apply. A answers yes or no with test. These two cover most of the lambdas you will write.
A takes nothing and hands back a value with get, handy for making something only when it is needed. A takes a value and gives nothing back with accept, like printing or saving it.
They snap together. f.andThen(g) runs f, then feeds its answer to g. p.and(q) needs both predicates to say yes, and p.negate() flips the answer.
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Function<String, String> tidy = text -> text.trim();
Function<String, Integer> size = text -> text.length();
Predicate<String> isLong = text -> text.length() > 5;
Supplier<String> fallback = () -> "anonymous";
Consumer<String> show = text -> System.out.println("User: " + text);
String typed = " ziggy_stardust ";
System.out.println(tidy.andThen(size).apply(typed));
System.out.println(isLong.test(tidy.apply(typed)));
show.accept(fallback.get());
}
} In Function<String, Integer> the first type goes in and the last type comes out.
guess first
Who pays full price? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isAdult = age -> age >= 18;
Predicate<Integer> isSenior = age -> age >= 65;
Predicate<Integer> payFull = isAdult.and(isSenior.negate());
System.out.println(payFull.test(30));
System.out.println(payFull.test(70));
System.out.println(payFull.test(12));
}
}
your turn
Your turn. Build a price tag machine.
On line 7, chain the three steps with andThen so the price gets VAT, then rounds up, then gets its label.
output
press run to see what happens
fix it
The vowel counter will not compile. Can you fix it?
output
press run to see what happens
- Java cannot find a method on line 8. Which method does a
Predicatehave? applybelongs toFunction. APredicateanswers yes or no with a different method.- Change
isVowel.apply(letter)toisVowel.test(letter)on line 8, then run.
nailed it
you know java's ready-made lambda types. :D
Functionapplies,Predicatetests,Suppliergets,Consumeraccepts.andThenchains functions, one after another.andandnegatebuild new predicates from old ones.
new words in your collection
- Function
- Predicate
- Supplier
- Consumer
This lesson isn’t saved. A free account remembers every lesson you finish.