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.function.Consumer;
public static void main(String[] args) {
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:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public static void main(String[] args) {
Consumer<String> say = a -> System.out.println("Hello, " + a + "!");
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:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public static void main(String[] args) {
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:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public static void main(String[] args) {
Consumer<String> say = a -> System.out.println("Hello, " + a + "!");
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.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public static void main(String[] args) {
Consumer<String> say = a -> System.out.println("Hello, " + a + "!");
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);
upperCaseConsumer.andThen(sayAll).accept(musketeers);
}