What is Consumer Interface in Java?
1 min readThis lesson talks about the first functional interface, which is the Consumer.
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>
Consumer methods
This functional interface has two methods
- accept
- andThen
accept
This operation is performed on the given argument. Let's 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);
}
}
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.
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.