Jul 172015

A functional interface is an interface that specifies exactly one abstract method. in Java8 interfaces can now also have default methods (that is, a method with a body that provides some default implementation for a method in case it isn’t implemented by a class). An interface is still a functional interface if it has many default methods as long as it specifies only one abstract method.

Some interfaces that we can consider as functional interfaces are:

Lambda expressions let you provide the implementation of the abstract method of a functional interface directly inline and treat the whole expression as an instance of a functional interface, that is, as an instance of a concrete implementation of the functional interface. For example, the following codes are equivalents:

We can use @FuntionalInterface as an informative annotation type to indicate that an interface type declaration is intended to be a functional interface. Compilers are required to generate an error message if the annotated interface does not satisfy the requirements of a functional interface. However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

Some of the most important functional interfaces in Java 8, that you can find them in java.util.function package, are:

Interface name Arguments Returns Example
Consumer<T> T void String s -> System.out.println(s)
BiConsumer<T, U> T, U void (k, v) -> System.out.println("key:"+ k + ", value:"+ v)
Supplier<T> None T () -> createLogMessage()
Function<T, R> T R Student s -> s.getName()
BiFunction<T,U,R> T, U R (String name, Student s) -> new Teacher(name, student)
UnitaryOperator<T> T T String s -> s.toLowerCase()
BinaryOperator<T> T, T T (String x, String y)-> {
  if (x.length() > y.length()) return x;
  return y;
Predicate<T> T boolean Student s -> s.graduationYear() == 2011

Related posts:
Lambda expressions in Java 8

Sorry, the comment form is closed at this time.