Java consumer

Introduction

Applying

Introduced in Java 8, the Consumer interface aims at providing additional functional programming capabilities for Java.

Consumer defined functions do not return any value and they consist mainly of two methods:

void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after);

Let's look at an example:

import java.util.ArrayList; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.function.Consumer; 

Consumer<String> say = a -> System.out.println("Hello, " + a + "!"); 

say.accept("World"); 
Hello, World!

A Consumer can be applied in a functional way, since applying a consumer is equivalent to applying the accept method. For instance:

List<String> musketeers = new ArrayList<String>();
musketeers.add("D'Artagnan");
musketeers.add("Athos");
musketeers.add("Aramis");
musketeers.add("Porthos");
musketeers.stream().forEach(say)
Hello, D'Artagnan!
Hello, Athos!
Hello, Aramis!
Hello, Porthos!

Consumer functions can also modify reference objects. For instance:

List<Double> numbers = new ArrayList<Double>(); 
numbers.add(1d); 
numbers.add(2d); 
numbers.add(3d); 

Consumer<List<Double>> square = list -> {
    for (int i = 0; i < list.size(); i++) {
        double x = list.get(i);
        list.set(i, x*x); 
    };
};

System.out.println(numbers);

square.accept(numbers);

System.out.println(numbers);
[1.0, 2.0, 3.0]
[1.0, 4.0, 9.0]

Composing

Let's now look at how to create a chain of Consumers by composing them with the andThen method. Let's first create a consumer which converts a string to uppercase in-place:

Consumer<List<String>> upperCaseConsumer = list -> {
        for(int i=0; i< list.size(); i++){
            String value = list.get(i).toUpperCase();
            list.set(i, value);
        }
    };

Consumer<List<String>> sayAll = list -> list.stream().forEach(say);

We will now create a chain by first applying upperCaseConsumer and the say to our list.

upperCaseConsumer.andThen(sayAll).accept(musketeers);
Hello, D'ARTAGNAN!
Hello, ATHOS!
Hello, ARAMIS!
Hello, PORTHOS!