Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.

Java 8 Revealed: Lambdas, Default Methods and Bulk Data Operations

Functional interfaces

As we learned, the runtime representation of a lambda is a functional interface (or a SAM type), an interface that defines only one abstract method. And although JDK already includes a number of interfaces, like Runnable and Comparator, that match the criteria, it is clearly not enough for API evolution. It just wouldn’t be as logical if we started using Runnables all around the code.

There’s a new package in JDK8, java.util.function, that includes a number of functional interfaces that are intended to be used by the new API. We won’t list all of them here – just do yourself a favour and study the package yourself :)

Here’s just a few interesting interfaces defined in the above mentioned package of the JDK library:

  • Consumer<T> – performs an action on type T without returning a result.
  • Supplier<T> – returns an instance of type T, no input required.
  • Predicate<T> – consumes an instance of type T as a parameter and produces boolean value.
  • Function<T,R> – takes instance of type T as a parameter and produces an instance of type R as a result.

Your time is too valuable to sit around waiting for your code to redeploy. Seriously, imagine how much more you could accomplish if you choose to Eliminate Redeploys from your daily routine!

There are over 40 new functional interfaces defined in the java.util.function package. Often the intention of the interface can be derived from the name. For instance, BiFunction is very similar to the Function interface mentioned above, with the only difference that it takes two input parameters instead of one.

An other common pattern that we could see in the new set of interfaces is when an interface extends the other interface in order to define the same type for multiple parameters. For instance, BinaryOperator extends BiFunction, and the purpose is just to ensure that the two input arguments would be of the same type.

public interface BinaryOperator extends BiFunction<T,T,T> {}

To emphasise the intention of an interface to be used as a functional one, the new @FunctionalInterface annotation can be applied to prevent your team mates from adding new method declarations into the interface. Aside of its runtime presence the annotation is used by javac to verify if the interface is really a functional interface and there’s no more than one abstract method in it.

The following code will not compile:

interface Action {
  void run(String param);
  void stop(String param);

The compiler throw an error:

java: Unexpected @FunctionalInterface annotation
    Action is not a functional interface
    multiple non-overriding abstract methods found in interface Action

But the following will compile just fine:

interface Action {
  void run(String param);
  default void stop(String param){}

Download the PDF