IntConsumer 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 expect a single int-valued argument as input but produces no output. In this post, we are going to see several implementations of IntConsumer Interface by using different examples.
IntConsumer Interface in Java 8 with Examples...!!! Click To Tweet
Look at IntConsumer Javadoc description below:
IntConsumer Interface contains 2 methods:
accept
andThen
Let’s discuss these methods:
accept
This method performs operation on the given argument and return no result.
1 | void accept(int value); |
Below are the several examples to demonstrate accept() method:
Example 1. ‘accept’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.function.IntConsumer; public class IntConsumerInterfaceJava8Example1 { public static void main(String args[]) { System.out.println("Ex. 1 - accept method \n"); IntConsumer intConsumerObj = d -> System.out.println(d + 100); intConsumerObj.accept(10); } } |
andThen
This method returns a composed IntConsumer 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 IntConsumer andThen(IntConsumer after) { Objects.requireNonNull(after); return (int t) -> { accept(t); after.accept(t); }; } |
Below are the several examples to demonstrate andThen() method:
Example 2. ‘andThen’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.function.IntConsumer; public class IntConsumerInterfaceJava8Example2 { public static void main(String args[]) { System.out.println("Ex. 2 - andThen method \n"); IntConsumer intConsumerObj1 = d -> System.out.println(d + 100); IntConsumer intConsumerObj2 = d -> System.out.println(d * 2); //andThen operation intConsumerObj1.andThen(intConsumerObj2).accept(10); } } |
Java 8 IntConsumer Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.
IntConsumer 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
Other Useful References: