What is Consumer Interface in Java?
This lesson talks about the first functional interface, which is the Consumer.
Table of Contents
What is a Consumer Interface?
It takes a single argument and returns nothing, that is why it is called Consumer. Because it consumes a value.
In other words, represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, the Consumer
is expected to operate via side effects.
This is a functional interface
whose functional method is accept(Object)
.
Syntax:
Consumer<T>
Methods
This functional interface has two methods
- accept
- andThen
1. accept
Performs this operation on the given argument. Let us see an example snippet that converts the string to lowercase.
This is the proper and correct syntax.
Syntax:
void accept(T t);
Code
import java.util.function.Consumer;
public class ConsumerAccept {
public static void main(String[] args) {
print(100);
}
public static void print(int number) {
Consumer<Integer> consumer = A -> System.out.println(A * 2);
consumer.accept(number);
}
}
2. andThen
This method returns a composed Consumer that performs, in sequence, this operation followed by the after
operation.
If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after
operation will not be performed.
Syntax:
default Consumer<T> andThen(Consumer<? super T> after);
It is creating a new Consumer for each call to andThen,
finally, at the end, it invokes the accept
method which is the only abstract one.
Code
import java.util.function.Consumer;
public class ConsumerAndThen {
public static void main(String[] args) {
print(100, 2, 5);
}
public static void print(int A, int firstMultiplier, int secondMultiplier) {
Consumer<Integer> firstConsumer = number -> System.out.println(number * firstMultiplier);
Consumer<Integer> secondConsumer = number -> System.out.println(number * secondMultiplier);
Consumer<Integer> thirdConsumer = firstConsumer.andThen(secondConsumer);
// accept
thirdConsumer.accept(A);
}
}
In lines 9 and 10, we created two Consumers, firstConsumer
and secondConsumer
, that respectively multiply the given input 100
by 2
and 5
.
We created our third Consumer
in line 12, using the andThen(...)
method.
👨🏻💻 Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.