Understanding Java 8’s Consumer, Supplier, Predicate and Function
Functional programming in Java in a better way.
Java has introduced functional programming support in Java release version 8. This specific release has also introduced several new concepts notably lambda expressions, method reference and a plethora of functional interfaces. While discussing functional interfaces, there are few functional interfaces namely Consumer, Supplier, Predicate and Functions are most crucial. In this article, we will talk about these interfaces.
Consumer
A Consumer is a functional interface that accepts a single input and returns no output. In layman’s language, as the name suggests the implementation of this interface consumes the input supplied to it. Consumer interface has two methods:
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after);
The accept method is the Single Abstract Method (SAM) which accepts a single argument of type T. Whereas, the other one andThen is a default method used for composition.
Following is an example of a consumer interface. We have created a consumer implementation that consumes a String and then prints it. The forEach method accepts consumer interface implementation.