Member-only story
Primitive Consumer Interfaces in Java: IntConsumer, LongConsumer, and DoubleConsumer
1. Introduction to Primitive Consumer Interfaces
Hello everyone, welcome back! In this blog post, we’ll talk about three important primitive Consumer functional interfaces in Java: IntConsumer
, LongConsumer
, and DoubleConsumer
. These interfaces are specialized versions of the Consumer<T>
interface but are designed to work with primitive types (int
, long
, and double
). Using these primitive consumers helps us avoid the overhead of autoboxing and unboxing, making our code faster and more memory efficient. Let’s dive in!
For free, you can read this article on my blog: IntConsumer, LongConsumer, and DoubleConsumer in Java.
2. What is Autoboxing?
Before we explore the primitive consumer interfaces, let’s briefly talk about autoboxing. Autoboxing is the automatic conversion of primitive types like int
, long
, and double
into their corresponding wrapper classes: Integer
, Long
, and Double
. While convenient, autoboxing introduces overhead because every primitive value must be wrapped in an object, leading to more memory usage and slower execution.
2.1 Example: Autoboxing with Consumer<Integer>
import java.util.function.Consumer;
public class AutoboxingExample {
public static void main(String[] args) {
// Consumer<Integer> causes autoboxing…