What is the IntConsumer functional interface in Java?
IntConsumer is a functional interface that accepts an int argument and returns no result. The interface contains two methods:
acceptandThen
The IntConsumer interface is defined in the java.util.function package. To import the IntConsumer interface, use the following import statement.
import java.util.function.IntConsumer;
The accept method
The accept method accepts a single integer input and performs the given operation on the input without returning a result.
Syntax
void accept(int value)
Parameters
value: The input argument.
Return value
The method doesn’t return a result.
Code
import java.util.function.*;public class Main{public static void main(String[] args) {// Implementation of IntConsumer interface that consumes and prints the passed valueIntConsumer intConsumer = (t) -> System.out.println("The passed parameter is - " + t);int parameter = 100;// calling the accept method to execute the print operationintConsumer.accept(parameter);}}
In the code above, we create an implementation of the IntConsumer interface that prints the passed integer argument to the console.
The andThen method
The andThen method is used to chain multiple IntConsumer implementations one after another and returns a composed IntConsumer of different implementations defined in order. If the evaluation of any IntConsumer implementation along the chain throws an exception, it is relayed to the caller of the composed function.
Syntax
default IntConsumer andThen(IntConsumer after)
Parameters
after: The next implementation ofIntConsumerto evaluate.
Return value
The method returns a composed IntConsumer that performs the
defined operation, followed by the after operation.
Code
import java.util.function.IntConsumer;public class Main{public static void main(String[] args) {IntConsumer intConsumerProduct = i -> System.out.println("Product Consumer - " + (i * 10));IntConsumer intConsumerSum = i -> System.out.println("Sum Consumer - " + (i + 10));int parameter = 9;// Using andThen() methodIntConsumer intConsumerComposite = intConsumerSum.andThen(intConsumerProduct);intConsumerComposite.accept(parameter);}}
In the code above, we define the following implementations of the IntConsumer interface:
intConsumerProduct: This implementation prints the result of the passedintvalue multiplied by10.intConsumerSum: This implementation prints the result of the sum of passedintvalue and10.
In line 12, we use the andThen method to chain the implementations.