Java 8 Consumer

 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.

@Test
public void whenNamesPresentConsumeAll(){
Consumer<String> printConsumer = t -> System.out.println(t);
Stream<String> cities = Stream.of("Sydney", "Dhaka", "New York", "London");
cities.forEach(printConsumer);
In the following example, we demonstrate the usage of composing multiple consumer implementations to make a chain of consumers. In this specific example, we have created two consumers; one converts a list of items into upper case Strings and the other one prints the uppercased string.
@Test
public void whenNamesPresentUseBothConsumer(){
List<String> cities = Arrays.asList("Sydney", "Dhaka", "New York", "London");
Consumer<List<String>> upperCaseConsumer = list -> {
for(int i=0; i< list.size(); i++){
list.set(i, list.get(i).toUpperCase());
}
};
Consumer<List<String>> printConsumer = list -> list.stream().forEach(System.out::println);
upperCaseConsumer.andThen(printConsumer).accept(cities);

Consumer interface has specific implementation types for integer, double and long types with IntConsumer, DoubleConsumer, and LongConsumer as shown below:

IntConsumer void accept(int x);
DoubleConsumer void accept(double x);
LongConsumer void accept(long x);

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Find Loop in a Linked List

Customized Immutable Class