What is the DoubleConsumer functional interface in Java?

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

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

1. accept

This method accepts a single double input and performs the given operation on the input without returning any result.

Syntax

void accept(double value)

Parameters

  • double value - The input argument.

Return value

The method doesn’t return any result.

Code

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 value
DoubleConsumer doubleConsumer = (t) -> System.out.println("The passed parameter is - " + t);
double parameter = 1002.32;
// calling the accept method to execute the print operation
doubleConsumer.accept(parameter);
}
}

In the code above, we created an implementation of the DoubleConsumer interface that prints the passed double argument to the console.

2. 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.

Syntax

default DoubleConsumer andThen(DoubleConsumer after)

Parameters

  • DoubleConsumer after - The next implementation of the DoubleConsumer to evaluate.

Return value

The method returns a composed DoubleConsumer that performs the operation in a sequence defined.

Code

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

Free Resources