How to Use a Functional Interface in Java
A functional interface is an interface that contains a single abstract method. It is used as the basis for lambda expressions in functional programming.
Such an interface may contain also other non-abstract methods even though this is not considered a good practice. Also, the notation @FunctionalInterface is optional but it will ensure that the intention of the interface is clear and the Java compiler will make sure the code conforms to the rules for functional interfaces.
Here is an example with finding cars that can fly by checking the boolean value of the canFly property of the Car objects:
class Car {
private String name;
private boolean canFly;
public Car(String name, boolean canFly) {
this.name = name;
this.canFly = canFly;
}
public boolean canFly() {
return canFly;
}
public String toString() {
return name;
}
}
@FunctionalInterface
interface CheckIfCanFly {
public boolean test(Car a);
}
public class FindFlyingCars {
private static void print(Car car, CheckIfCanFly fly) {
if (fly.test(car)) {
System.out.printf("%s can fly.", car);
}
}
public static void main(String[] args) {
print(new Car("Pal-v", true), a -> a.canFly());
print(new Car("Tesla", false), a -> a.canFly());
}
}
The above will print that Pal-v can fly. Tesla can't (yet).