DoubleConsumer Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expects a single double-valued argument as an input and produces no output. In this post, we are going to see several implementations of DoubleConsumer Interface by using different examples.
DoubleConsumer Interface in Java 8 with Examples...!!! Click To Tweet
Look at DoubleConsumer Javadoc description below:
DoubleConsumer Interface contains 2 methods:
accept
andThen
Let’s discuss these methods:
accept
This method accepts one input argument and performs operation on the given argument.
1 | void accept(double value); |
Below is an example to demonstrate accept() method:
Example 1. ‘accept’ method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.function.DoubleConsumer; public class DoubleConsumerInterfaceJava8Example1 { public static void main(String args[]) { System.out.println("Ex. 1 - 'accept' method \n"); DoubleConsumer doubleConsumerObj = d -> System.out.println(d + 100); doubleConsumerObj.accept(10); } } |
andThen
This method returns a composed DoubleConsumer that performs, in sequence, this operation followed by the after operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after operation will not be performed.
1 2 3 4 | default DoubleConsumer andThen(DoubleConsumer after) { Objects.requireNonNull(after); return (double t) -> { accept(t); after.accept(t); }; } |
Below is an example to demonstrate andThen() method:
Example 2. ‘andThen’ method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.function.DoubleConsumer; public class DoubleConsumerInterfaceJava8Example2 { public static void main(String args[]) { System.out.println("Ex. 2 - 'andThen' method \n"); DoubleConsumer addHundredDCObj = d -> System.out.println(d + 100); DoubleConsumer divideByTenDCObj = d -> d /= 5; //andThen operation DoubleConsumer result = divideByTenDCObj.andThen(addHundredDCObj); result.accept(5); } } |
DoubleConsumer Interface in Java 8 with Examples...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Generate Prime numbers in Java 8