Modern Java 8+ Features · Lambdas and Functional Interfaces
Java's four everyday lambda types: test a value, transform it, use it, or make one. Combine them with andThen.
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class FunctionalInterfacesDemo {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0; // takes a value, answers true/false
Function<Integer, Integer> square = n -> n * n; // takes a value, returns a value
Consumer<String> shout = s -> System.out.println(s.toUpperCase()); // takes a value, returns nothing
Supplier<String> greeting = () -> "hello"; // takes nothing, returns a value
boolean even = isEven.test(4);
int sq = square.apply(5);
shout.accept(greeting.get());
Function<Integer, Integer> squarePlusOne = square.andThen(n -> n + 1);
int combined = squarePlusOne.apply(3);
System.out.println(even + " " + sq + " " + combined);
}
}test runs the Predicate: is 4 even?even.apply runs the Function on 5.sq.shout.accept(greeting.get()).lambda$main$2(), with s = "hello". It gets its own variables on the stack.lambda$main$1(), with n = 3. It gets its own variables on the stack.lambda$main$4() has finished, so its variables are gone.combined.true 25 10.