Consumer Interface

Lambda

Consumer Interface


Consumer<T> is a built-in functional interface included in Java SE 8 in the java.util.function package. Consumer is used when an object should be taken as input and some operation should be performed on the object without returning any result. 

Example 1. java.util.function.Consumer Interface

The definition of the interface is shown in the example:

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    ...
}

Function descriptor is:

T -> void

Common example of using Consumer interface is printing:

Example 2. Use of java.util.function.Consumer interface in Lambda Expression

public class Exam {
    private String name;
    private String version;

    public Exam(String name, String version) {
        this.name = name;
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }
}
Consumer<Exam> consumer = e -> System.out.println(e.getName() +
         " " + e.getVersion());
consumer.accept(new Exam("OCPJP", "8"));
consumer.accept(new Exam("OCJP", "6"));

The Consumer interface also has the default method, which returns a composed Consumer that performs, in sequence, the operation of the consumer followed by the operation of the parameter:

default Consumer<T> andThen(Consumer<? super T> after)

Example 3. Usage of the default method andThen of java.util.function.Consumer interface

Let's view at the example which uses andThen method:

Consumer<String> first = t -> System.out.println(t.toUpperCase());
Consumer<String> second = t -> System.out.println(t.toLowerCase());
first.andThen(second).accept("Hello world");

The output is:

HELLO WORLD
hello world

 

Sources: Chapter TEN - Java Built-In Lambda Interfaces, Java 8 Programmer II Study Guide by Esteban Herrera.



0 comments
Leave your comment: