LongConsumer 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 long-valued argument as input but produces no output. In this post, we are going to see several implementations of LongConsumer Interface by using different examples.
LongConsumer Interface in Java 8 with Examples...!!! Click To Tweet
Look at LongConsumer Javadoc description below:
LongConsumer 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(long value); |
Below is an example 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.LongConsumer; public class LongConsumerInterfaceJava8Example1 { public static void main(String args[]) { System.out.println("Ex. 1 - accept method \n"); LongConsumer longConsumerObj = d - > System.out.println(d + 100); longConsumerObj.accept(10); } } |
andThen
This method returns a composed LongConsumer 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 LongConsumer andThen(LongConsumer after) { Objects.requireNonNull(after); return (long t) -> { accept(t); after.accept(t); }; } |
Below is an example to demonstrate andThen() method:
Example 2. ‘andThen’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import java.util.function.LongConsumer; public class LongConsumerInterfaceJava8Example2 { public static void main(String args[]) { System.out.println("Ex. 2 - andThen method \n"); //Long Consumer anonymous implementation LongConsumer longConsumerObj1 = new LongConsumer() { @Override public void accept(long value) { System.out.println("Object 1: " + value + 100); } }; //Long Consumer anonymous implementation LongConsumer longConsumerObj2 = new LongConsumer() { @Override public void accept(long value) { System.out.println("Object 2: " + value * 2); } }; //andThen operation longConsumerObj1.andThen(longConsumerObj2).accept(5); longConsumerObj2.andThen(longConsumerObj1).accept(25); } } |
LongConsumer 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