LongConsumer Interface in Java with Examples

The java.util.function package, which was first released with Java 8, includes the LongConsumer Interface, which is used to do functional programming in Java. It is an example of a function that accepts a single long-valued argument but outputs nothing. An object of the LongConsumer type is assigned a lambda expression, which is used to create its accept() function, which ultimately applies the specified operation on its single argument. Using an object of type Consumer<Long> is comparable. There are two functions which together make up the LongConsumer interface:

  1. accept()
  2. andThen()

1. accept():

This function takes a single parameter, which is its only value, and evaluates it.

Syntax:

Parameters:

The only parameter that the function takes is value, which is an argument.

Returns: There is no value returned by this method.

Example 1:

The Java program that is given shows how to use the LongConsumer interface to manipulate a long value.

Implementation:

FileName: LongConsumerValueprediction.java

Output:

The value is given by :40

Example 2:

The Java program that is given shows how to execute sequential operations on a long value using the LongConsumer interface.

Implementation:

FileName: SquaredValue.java

Output:

The Original value is given by : 12345
The Squared value is given by : 152399025

2. andThen():

It returns back a created LongConsumer, in which the parameterized LongConsumer will run after the initial one. An error is reported to the caller of the composite operation if the evaluation of either operation returns an error.

Note: It is required that the operation that is given as an argument be of the LongConsumer type.

Syntax:

Parameters: The LongConsumer that will be applied after the current one is accepted as a parameter by this method.

Return Value: This function's result is a created LongConsumer that applies the after operation after applying the current operation.

Exception: If the after operation is null, then this method raises a NullPointerException.

Example 1:

The given Java program shows how to execute and chain operations on a long value using the LongConsumer interface.

Implementation:

FileName: Valueprediction.java

Output:

The value is given by: 40

Example 2:

The below Java program shows how to use the andThen function of the LongConsumer interface to handle a NullPointerException.

Implementation:

FileName: NullPointerExceptionthrown.java

Output:

The Exception thrown is : java.lang.NullPointerException