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

UnaryOperator.identity(): The Identity Function

Understand the static identity() method that returns its input unchanged, useful as a default or placeholder.

UnaryOperator.identity(): The Identity Function

You'll learn what the identity() method is and when this "do-nothing" function becomes surprisingly useful.

What Is the Identity Function?

The UnaryOperator.identity() static method returns a special function that simply returns whatever input it receives, unchanged. It's the functional equivalent of saying "just pass it through."

Think of it like a transparent window—whatever you look at through it appears exactly as it is, with no transformation applied.

The Method Signature

static <T> UnaryOperator<T> identity()

This returns a UnaryOperator<T> where apply(x) always returns x.

When Is This Useful?

You might wonder why you'd need a function that does nothing. Here are common scenarios:

1. Default Behavior: When a method requires a UnaryOperator but you don't want any transformation:

List<String> words = Arrays.asList("Hello", "World");

// Apply identity - no transformation
UnaryOperator<String> noChange = UnaryOperator.identity();
words.replaceAll(noChange);
// words is still ["Hello", "World"]

2. Placeholder in Complex Logic: When building flexible systems where transformation is optional:

UnaryOperator<Integer> transform = 
    shouldDouble ? n -> n * 2 : UnaryOperator.identity();

int result = transform.apply(5); // 5 if no transform, 10 if doubling

3. Method Reference Alternative: Instead of writing x -> x, use the clearer UnaryOperator.identity().

Why Not Just Use a Lambda?

You could write x -> x, but identity() is:

  • More explicit about intent
  • Reuses the same singleton instance (memory efficient)
  • Self-documenting code

Key Takeaway: UnaryOperator.identity() returns a function that passes its input through unchanged—useful as a default, placeholder, or explicit "no transformation" signal in functional pipelines.