✅ What do they have in common?
They are all specialized versions of UnaryOperator<T>
for Java primitives: double
, int
, and long
.
➤ Why use them?
To avoid autoboxing and unboxing, which happens with generic types like UnaryOperator<Integer>
→ it’s slower and memory-intensive.
🔷 1. DoubleUnaryOperator
➤ Signature:
@FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
}
➤ Example:
DoubleUnaryOperator half = d -> d / 2.0;
System.out.println(half.applyAsDouble(10.0)); // 5.0
🔷 2. IntUnaryOperator
➤ Signature:
@FunctionalInterface
public interface IntUnaryOperator {
int applyAsInt(int operand);
}
➤ Example:
IntUnaryOperator increment = i -> i + 1;
System.out.println(increment.applyAsInt(9)); // 10
🔷 3. LongUnaryOperator
➤ Signature:
@FunctionalInterface
public interface LongUnaryOperator {
long applyAsLong(long operand);
}
➤ Example:
LongUnaryOperator doubleIt = l -> l * 2;
System.out.println(doubleIt.applyAsLong(10000000000L)); // 20000000000
✅ Summary Table
Interface | Input Type | Output Type | Method | Avoids Boxing? |
---|---|---|---|---|
UnaryOperator<T> | T | T | apply(T t) | ❌ No |
DoubleUnaryOperator | double | double | applyAsDouble() | ✅ Yes |
IntUnaryOperator | int | int | applyAsInt() | ✅ Yes |
LongUnaryOperator | long | long | applyAsLong() | ✅ Yes |