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...!!! Share on X
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.
void accept(long value);
Below is an example to demonstrate accept() method:
Example 1. ‘accept’
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.
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’
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);
}
}
Java 8 LongConsumer 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.
LongConsumer Interface in Java 8 with Examples...!!! Share on X
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