×

java · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.