Built-in Functional Interfaces

The JDK 1.8 API contains many built-in functional interfaces. Some of them are well known from older versions of Java like Comparator or Runnable. Those existing interfaces are extended to enable Lambda support via the @FunctionalInterface annotation.

But the Java 8 API is also full of new functional interfaces to make your life easier. Some of those new interfaces are well known from the Google Guava library. Even if you’re familiar with this library you should keep a close eye on how those interfaces are extended by some useful method extensions.

Predicates

Predicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate)

  1. Predicate<String> predicate = (s) -> s.length() > 0;
  2. predicate.test("foo"); // true
  3. predicate.negate().test("foo"); // false
  4. Predicate<Boolean> nonNull = Objects::nonNull;
  5. Predicate<Boolean> isNull = Objects::isNull;
  6. Predicate<String> isEmpty = String::isEmpty;
  7. Predicate<String> isNotEmpty = isEmpty.negate();

Functions

Functions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen).

  1. Function<String, Integer> toInteger = Integer::valueOf;
  2. Function<String, String> backToString = toInteger.andThen(String::valueOf);
  3. backToString.apply("123"); // "123"

Suppliers

Suppliers produce a result of a given generic type. Unlike Functions, Suppliers don’t accept arguments.

  1. Supplier<Person> personSupplier = Person::new;
  2. personSupplier.get(); // new Person

Consumers

Consumers represent operations to be performed on a single input argument.

  1. Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
  2. greeter.accept(new Person("Luke", "Skywalker"));

Comparators

Comparators are well known from older versions of Java. Java 8 adds various default methods to the interface.

  1. Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
  2. Person p1 = new Person("John", "Doe");
  3. Person p2 = new Person("Alice", "Wonderland");
  4. comparator.compare(p1, p2); // > 0
  5. comparator.reversed().compare(p1, p2); // < 0