What is LongConsumer functional interface in Java?

LongConsumer is a functional interface that accepts a long argument and returns no result. The interface contains two methods:

  1. accept
  2. 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;

1. The accept method

The accept method accepts a single long input and performs the given operation on the input without returning any result.

Syntax

void accept(long value)

Parameters

  • long value: The input argument.

Return value

The method doesn’t return any result.

Code

import java.util.function.*;
public class Main{
public static void main(String[] args) {
// Implementation of LongConsumer interface that consumes and prints the passed value
LongConsumer longConsumer = (t) -> System.out.println("The passed parameter is - " + t);
long parameter = 100232;
// calling the accept method to execute the print operation
longConsumer.accept(parameter);
}
}

In the code above, we create an implementation of the LongConsumer interface that prints the passed long argument to the console.

2. The andThen method

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.

Syntax

default LongConsumer andThen(LongConsumer after)

Parameters

  • LongConsumer after: The next implementation of the LongConsumer to evaluate.

Return value

The method returns a composed LongConsumer that performs in sequence the operation defined followed by the after operation.

Code

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() method
LongConsumer 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.

Free Resources