LongConsumer
is a functional interface that accepts a long
argument and returns no result. The interface contains two methods:
accept
andThen
The LongConsumer
interface is defined in the java.util.function
package. To import the LongConsumer
interface, check out the following import statement.
import java.util.function.LongConsumer;
The accept
method accepts a single long
input and performs the given operation on the input without returning any result.
void accept(long value)
long value
: The input argument.The method doesn’t return any result.
import java.util.function.*;public class Main{public static void main(String[] args) {// Implementation of LongConsumer interface that consumes and prints the passed valueLongConsumer longConsumer = (t) -> System.out.println("The passed parameter is - " + t);long parameter = 100232;// calling the accept method to execute the print operationlongConsumer.accept(parameter);}}
In the code above, we create an implementation of the LongConsumer
interface that prints the passed long
argument to the console.
The andThen
method is used to chain multiple LongConsumer
implementations one after another. The method returns a composed LongConsumer
of different implementations defined in the order. If the evaluation of any LongConsumer
implementation along the chain throws an exception, it is relayed to the caller of the composed function.
default LongConsumer andThen(LongConsumer after)
LongConsumer after
: The next implementation of the LongConsumer
to evaluate.The method returns a composed LongConsumer
that performs in sequence the operation defined followed by the after operation.
import java.util.function.LongConsumer;public class Main{public static void main(String[] args) {LongConsumer longConsumerProduct = i -> System.out.println("Product Consumer - " + (i * 10));LongConsumer longConsumerSum = i -> System.out.println("Sum Consumer - " + (i + 10));long parameter = 9432;// Using andThen() methodLongConsumer longConsumerComposite = longConsumerSum.andThen(longConsumerProduct);longConsumerComposite.accept(parameter);}}
In the code above, we define the following implementations of the LongConsumer
interface.
longConsumerProduct
: This implementation prints the result of the passed long
value multiplied by 10
.longConsumerSum
: This implementation prints the result of the sum of the passed long
value and 10
.In line 12, both the implementations are chained using the andThen
method.