Predicate takes a value, and answers true or false. Function takes a value, and returns another. Consumer takes a value, and returns nothing. And Supplier takes nothing, and gives back a value.
Is long is a predicate, tested with test. Length is a function, used with apply. Shout is a consumer, used with accept. And dice is a supplier, called with get. Run it. Banana is long, but fig isn't. Java has four letters. Hello is shouted. And the dice gives a number from one to six.
Main.javajava
import java.util.function.*;public class Main { public static void main(String[] args) { Predicate<String> isLong = s -> s.length() > 5; Function<String, Integer> length = s -> s.length(); Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!"); Supplier<Double> dice = () -> Math.floor(Math.random() * 6) + 1; System.out.println(isLong.test("banana") + " " + isLong.test("fig")); System.out.println(length.apply("Java")); shout.accept("hello"); double roll = dice.get(); System.out.println("Dice is 1 to 6? " + (roll >= 1 && roll <= 6)); }}
You can write your own functional interface. Discount has one method, apply. Show accepts any discount, as a lambda. Each call passes different behaviour. Run it. Eighty, forty, and sixty five.
Main.javajava
public class Main { @FunctionalInterface interface Discount { double apply(double price); } static void show(String label, Discount d) { System.out.printf("%-10s %.2f%n", label, d.apply(80)); } public static void main(String[] args) { show("None", p -> p); show("Half", p -> p / 2); show("Minus 15", p -> p - 15); }}
A functional interface has one abstract method, and a lambda fills it in. Predicate, Function, Consumer, and Supplier are the most common. Next, an even shorter form, method references.