Java 8 (LTS) · Topic 3 of 12
Functional interfaces
Definition​
A functional interface has exactly one abstract method, so a lambda can stand in for it. Java provides common ones: Function (input to output), Predicate (yes or no), Supplier (gives a value) and Consumer (uses a value).
Example code​
The four built-in shapes, and your own
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
@FunctionalInterface
interface Discount { // your own functional interface
int apply(int price);
}
class Demo {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
Predicate<Integer> isEven = n -> n % 2 == 0;
Supplier<String> greeting = () -> "Hello";
Consumer<String> printer = s -> System.out.println("Got: " + s);
Discount tenPercent = price -> price * 90 / 100;
System.out.println(length.apply("lambda"));
System.out.println(isEven.test(7));
printer.accept(greeting.get());
System.out.println(tenPercent.apply(200));
}
}
// Output:
// 6
// false
// Got: Hello
// 180
Finished this page? Track your progress (saved only in your browser).