UnaryOperator<T>: Concept and Purpose
What you'll learn: You'll understand UnaryOperator<T> as a specialized functional interface for transformations where input and output share the same type.
What is UnaryOperator<T>?
UnaryOperator<T> is a functional interface that extends Function<T, T>. While Function<T, R> can transform one type into another, UnaryOperator<T> is specifically designed for operations where both the input and output are the same type.
Think of it like a filter on your phone camera: you put in a photo and get back a modified photo—same type in, same type out. Whether you're applying brightness, contrast, or a vintage effect, you're always working with images throughout.
Why Does It Exist?
You might wonder: "Why not just use Function<T, T>?" The answer is clarity and intent. When you see UnaryOperator<String>, you immediately know it transforms a String into another String. It's a semantic signal that makes your code more self-documenting.
Additionally, UnaryOperator<T> has only one type parameter instead of two, making declarations cleaner:
UnaryOperator<String> toUpper = s -> s.toUpperCase();
// vs
Function<String, String> toUpper = s -> s.toUpperCase();
Common Use Cases
- String transformations (trim, uppercase, replace)
- Numeric adjustments (double a value, round, negate)
- Object updates (increment a counter, modify a field)
- Mathematical operations (square, absolute value)
The Relationship to Function
Because UnaryOperator<T> extends Function<T, T>, it inherits the apply, andThen, and compose methods you already know. Everything that works with Function works here too.
Key Takeaway: UnaryOperator<T> is a specialized Function<T, T> that signals same-type transformations, making your code clearer and type declarations simpler.