Functional Interfaces


Collapse Content

In Java 8 a functional interface is defined as an interface with exactly one abstract method. This even applies to interfaces that were created with previous versions of Java.

Java 8 comes with several new functional interfaces in the package, java.util.function.

  • Function<T,R> - takes an object of type T and returns R.
  • Supplier<T> - just returns an object of type T.
  • Predicate<T> - returns a boolean value based on input of type T.
  • Consumer<T> - performs an action with given object of type T.
  • BiFunction - like Function but with two parameters.
  • BiConsumer - like Consumer but with two parameters.

It also comes with several corresponding interfaces for primitive types, such as:

  • IntConsumer
  • IntFunction<R>
  • IntPredicate
  • IntSupplier

See the java.util.function Javadocs for more information.


The coolest thing about functional interfaces is that they can be assigned to anything that would fulfill their contract. Take the following code for example:

Function<String, String> atr = (name) -> {return "@" + name;};
Function<String, Integer> leng = (name) -> name.length();
Function<String, Integer> leng2 = String::length;

This code is perfectly valid Java 8. The first line defines a function that prepends "@" to a String. The last two lines define functions that do the same thing: get the length of a String.

The Java compiler is smart enough to convert the method reference to String's length() method into a Function (a functional interface) whose apply method takes a String and returns an Integer.

For example:

for (String s : args) out.println(leng2.apply(s));

This would print out the lengths of the given strings.

Any interface can be functional interface, not merely those that come with Java. To declare your intention that an interface is functional, use the @FunctionalInterface annotation. Although not necessary, it will cause a compilation error if your interface does not satisfy the requirements (ie. one abstract method).

Challenge

How would you define the type declaration for a Function which takes in a Date and returns a String?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

How do you define a functional interface?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Modify the following interfaces so that the code compiles and runs properly. Read the main method but do not modify it.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]