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