The Java Consumer interface of the java.util.function package is a functional interface that is often used as an assignment target for lambda expressions. accept(T t) is the interface’s single abstract method which takes an object as input and returns nothing. The andThen(Consumer<? super T> after) method provides a simple way to string multiple Consumer objects together by calling accept() first on the object itself and then accept() on the object passed as the parameter.

For more information on functional interfaces in Java click here: What is a Java Functional Interface?.

Consumer Interface Source Code

@FunctionalInterface
public interface Consumer<T> {

    void accept(T t);

    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }

}

Consumer Interface Example

Creating the ConsumerExample class by implementing Consumer. The accept(T t) method takes a string and prints it.

public class ConsumerExample implements Consumer<String> {
    public void accept(String s) {
        System.out.println(s);
    }
}

Creating a Consumer Instance with Lambda Expression

Using a lambda expression to create an instance of Consumer. The accept(T t) method takes a string and prints it.

Consumer<String> consumer = t -> System.out.println(t);

Leave a Reply

What is the Java Consumer Interface?