The LongConsumer functional interface in Java is part of the java.util.function package and is commonly used for defining operations that consume a single long-valued argument and return no result. It’s a specialization of Consumer for the long primitive type.
The key method in LongConsumer is:
void accept(long value);
Using LongConsumer
Here’s how we can use the LongConsumer functional interface:
- Lambda Example: We can use a lambda expression to define the action for
accept. - Method Reference: We can pass a method reference as a
LongConsumer. - Combine Consumers: We can use the
andThenmethod to chain multipleLongConsumerinstances together.
Example 1: Using a Lambda Expression
package org.kodejava.util.function;
import java.util.function.LongConsumer;
public class LongConsumerExample {
public static void main(String[] args) {
LongConsumer printLong = value -> System.out.println("Value: " + value);
// Calling the accept method
printLong.accept(42L);
// Output: Value: 42
}
}
Example 2: Method Reference
We can also use a method reference if we already have a method that accepts a long and performs an operation.
package org.kodejava.util.function;
import java.util.function.LongConsumer;
public class LongConsumerMethodRef {
public static void main(String[] args) {
LongConsumer printLong = System.out::println;
// Calling the accept method
printLong.accept(100L);
// Output: 100
}
}
Example 3: Using andThen to Chain Consumers
The andThen method allows chaining multiple LongConsumer actions. It returns a composite LongConsumer that performs all the operations in sequence.
package org.kodejava.util.function;
import java.util.function.LongConsumer;
public class LongConsumerChaining {
public static void main(String[] args) {
LongConsumer printLong = value -> System.out.println("Printing value: " + value);
LongConsumer doubleValue = value -> System.out.println("Double of value: " + (value * 2));
LongConsumer combined = printLong.andThen(doubleValue);
// Calling the combined LongConsumer
combined.accept(25L);
// Output:
// Printing value: 25
// Double of value: 50
}
}
Practical Use Case
LongConsumer can be used in scenarios involving streams of long values, such as with the primitive specialization LongStream in the Java Stream API.
package org.kodejava.util.function;
import java.util.function.LongConsumer;
import java.util.stream.LongStream;
public class LongStreamExample {
public static void main(String[] args) {
LongConsumer printLong = value -> System.out.print(value + " ");
// Using LongConsumer with LongStream
LongStream.range(1, 5).forEach(printLong);
// Output: 1 2 3 4
}
}
Key Points:
- LongConsumer is a functional interface meant for operations on
longvalues. - It defines one abstract method,
accept(long value). - The
andThenmethod is a default method used to chain consumers together. - Useful in functional programming styles and with primitive streams like
LongStream.
