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

Using UnaryOperator with Lambda Expressions

Write concise lambdas like x -> x * 2 and use them with UnaryOperator for type-preserving transformations.

Using UnaryOperator with Lambda Expressions

What You'll Learn

You'll learn how to write concise lambda expressions that transform a value while keeping its type intact using UnaryOperator<T>.

The Core Idea

UnaryOperator<T> is a specialized functional interface that takes a single argument of type T and returns a result of the same type T. This makes it perfect for transformations where the input and output types match—like doubling a number, uppercasing a string, or incrementing a value.

The beauty of UnaryOperator is how naturally it pairs with lambda expressions. Instead of verbose syntax, you can write operations in their simplest form.

Lambda Syntax with UnaryOperator

The most compact lambda for a UnaryOperator follows this pattern:

UnaryOperator<Integer> doubler = x -> x * 2;

Here, x -> x * 2 takes an integer and returns an integer—doubled. No type declarations needed; Java infers them from the UnaryOperator<Integer> declaration.

Practical Examples

// String transformation
UnaryOperator<String> toUpper = s -> s.toUpperCase();
String result = toUpper.apply("hello"); // "HELLO"

// Numeric operation
UnaryOperator<Double> square = n -> n * n;
Double squared = square.apply(4.0); // 16.0

// Chaining with andThen
UnaryOperator<Integer> addFive = x -> x + 5;
UnaryOperator<Integer> multiplyByTwo = x -> x * 2;
UnaryOperator<Integer> combined = addFive.andThen(multiplyByTwo);
Integer value = combined.apply(3); // (3 + 5) * 2 = 16

Why Use UnaryOperator?

Think of UnaryOperator as a type-safe "same-in, same-out" transformer. It's clearer than Function<T, T> because the name itself communicates intent: "I'm operating on a value and returning the same type."

Key Takeaway: UnaryOperator<T> with lambdas like x -> x * 2 provides a concise, readable way to express single-argument, type-preserving transformations—perfect for operations like doubling numbers, formatting strings, or any modification that keeps the same data type.