Course contentsShow
← Java
Lesson 1688 of 2,87035. Functional InterfacesFree lesson

Primitive Specializations: IntUnaryOperator, LongBinaryOperator, etc.

Discover primitive operator variants like IntUnaryOperator and DoubleBinaryOperator to avoid boxing overhead.

Primitive Specializations: IntUnaryOperator, LongBinaryOperator, etc.

You'll learn how to avoid boxing overhead by using primitive-specialized operator interfaces.

The Boxing Problem

When you use UnaryOperator<Integer> or BinaryOperator<Double>, Java must box primitive values (like int or double) into wrapper objects (like Integer or Double) and unbox them repeatedly. This creates unnecessary object allocation and performance overhead, especially in tight loops or large streams.

Primitive Operator Interfaces

Java provides specialized functional interfaces for primitives that work directly with primitive types—no boxing required:

Unary Operators (one input, one output of the same type):

  • IntUnaryOperator: int → int
  • LongUnaryOperator: long → long
  • DoubleUnaryOperator: double → double

Binary Operators (two inputs, one output, all the same type):

  • IntBinaryOperator: (int, int) → int
  • LongBinaryOperator: (long, long) → long
  • DoubleBinaryOperator: (double, double) → double

When to Use Them

Use these specialized interfaces when:

  • Processing large amounts of numeric data
  • Working with primitive streams (IntStream, LongStream, DoubleStream)
  • Performance is critical and boxing overhead matters
// Inefficient: boxing overhead
UnaryOperator<Integer> boxed = x -> x * 2;

// Efficient: no boxing
IntUnaryOperator primitive = x -> x * 2;

// With BinaryOperator
DoubleBinaryOperator multiply = (a, b) -> a * b;

These interfaces use applyAsInt(), applyAsLong(), or applyAsDouble() instead of the generic apply() method, returning primitives directly.

Key Takeaway: Primitive specializations like IntUnaryOperator and DoubleBinaryOperator eliminate boxing overhead by working directly with primitive types, improving performance in numeric computations.