IntUnaryOperator, LongUnaryOperator, and DoubleUnaryOperator
What you'll learn: How to apply transformations on primitive integers, longs, and doubles without the performance overhead of autoboxing.
The Core Idea
While UnaryOperator<T> works with reference types (like UnaryOperator<Integer>), each operation triggers boxing and unboxing between primitives and wrapper objects. The specialized operators IntUnaryOperator, LongUnaryOperator, and DoubleUnaryOperator skip this conversion entirely, operating directly on primitive values for maximum efficiency.
Think of it like a specialized tool: you could use a multi-purpose adjustable wrench for every bolt, but a socket wrench sized exactly for your bolt is faster and more efficient.
The Three Primitive Unary Operators
Each interface has a single abstract method called applyAsInt, applyAsLong, or applyAsDouble:
IntUnaryOperator doubler = x -> x * 2;
int result = doubler.applyAsInt(5); // returns 10
LongUnaryOperator incrementer = x -> x + 1L;
long value = incrementer.applyAsLong(100L); // returns 101
DoubleUnaryOperator squarer = x -> x * x;
double squared = squarer.applyAsDouble(3.5); // returns 12.25
Composition with andThen and compose
Just like UnaryOperator, these support function composition:
IntUnaryOperator addTwo = x -> x + 2;
IntUnaryOperator multiplyByThree = x -> x * 3;
IntUnaryOperator combined = addTwo.andThen(multiplyByThree);
int result = combined.applyAsInt(5); // (5 + 2) * 3 = 21
IntUnaryOperator reversed = addTwo.compose(multiplyByThree);
int result2 = reversed.applyAsInt(5); // (5 * 3) + 2 = 17
These operators are particularly useful in stream operations when you need to transform primitive streams without boxing overhead.
Key Takeaway: Use IntUnaryOperator, LongUnaryOperator, and DoubleUnaryOperator to apply transformations on primitive values efficiently, avoiding the performance cost of boxing and unboxing that occurs with generic UnaryOperator<T>.