A lambda expression is used with a functional interface, i.e. an interface with one abstract method.
Functional interfaces may have default and static methods.
Some examples of functional interfaces are:
java.lang.Consumer, which only has the method accept().java.lang.Runnable, which only has the method run().java.lang.Comparable, which only has the method compareTo().java.lang.AutoCloseable, which only has the method close().The Helloable interface we saw in the beginning of this module is a functional interface.
public interface Helloable {
abstract void sayHello(Character character);
}And so is:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}And:
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}The interface for which a lambda expression is invoked is called its target type.
Helloable custom =
c -> System.out.println("Hello " + c.firstName.charAt(0) + ". " + c.lastName);
sayHelloEverybody(
characters,
c -> System.out.println("Hello " + c.firstName.charAt(0) + ". " + c.lastName));The target type of a lambda expression must
You can use lambda expressions in