Functional Interfaces in the java.util.function Package

Java 8 was released on 18 March 2014, with a bunch of new features and thus changed the way how we (as Java Developers) code.

If you explored the APIs that are part of Java 8 and especially those APIs which support lambda expressions you will find few interfaces like- Function, Supplier, Consumer, Predicate and others which are all part of the java.util.function package, being used extensively. These interfaces have one abstract method, which is overridden by the lambda expression defined.

Today, I'll cover throughout this post, the generic interfaces that belongs to the java.util.function package. Of course, You can review the package for more details.

Consumer< T >:

It's an operation that takes a single value and returns no result. Consumer can be used in all contexts where an object needs to be consumed,i.e. taken as input, and some operation is to be performed on the object without returning any result. Common example of such an operation is printing, where an object is taken as input to the printing function and the value of the object is printed

String s -> System.out.println(s)

(k, v) -> System.out.println("key:" + k + ", value:" + v)

Supplier< T >:

It's the opposite of a Consumer, which means that Supplier can be used in all contexts where there is no input but an output is expected.

() -> customLogMessage()

Function< T,R >

It's a function that accepts one argument and returns a result. The primary purpose for which Function<T, R> has been created is for mapping scenarios i.e when an object of a type is taken as input and its is converted(or mapped) to another type. Common usage of Function is in streams where-in the map function of a stream accepts an instance of Function to convert the stream of one type to a stream of another type.

Student s -> s.getName()

(String name, Student s) -> new Teacher(name, s)

UnaryOperator< T >

UnaryOperator is a specialized form of Function where the single argument and result of the same type.

String s -> s.toLowerCase()

BinaryOperator< T >

This one is also a specialized form of BiFunction, where two arguments and a result, all of the same type.

(String x, String y) -> {
  if (x.length() > y.length())
    return x;
  return y;
}

Predicate

Predicate is a Boolean valued function of one argument, which can be used in all the contexts where an object needs to be evaluated for a given test condition, and a boolean value needs to be returned based on whether the condition was successfully met or not.

Student s -> s.graduationYear() == 2011

Summary

As we've seen, the function package provides a range of functional interfaces, which are used extensively in Streams (as well s many other places).