Let’s dive into UnaryOperator<T>, which is a specialized version of Function<T, R> when input and output types are the same.
✅ UnaryOperator<T>
➤ Signature:
T apply(T t);
➤ It is a subinterface of:
Function<T, T>
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
T apply(T t);
}
➤ What does it do?
A UnaryOperator<T> represents a function that:
- Takes one argument of type
T - Returns a result of the same type
T
It’s just a specialized Function<T, T>, used when the transformation doesn’t change the type.
✅ Use Cases
- String or number transformations
- In-place modifications (like
.replaceAll(...)) - Mathematical operations
- Cleaner, more expressive code
➤ Use Case:
When you want to transform a value into another of the same type — for example, modifying strings, numbers, or objects in place.
✅ Example 1: String manipulation
UnaryOperator<String> toUpper = s -> s.toUpperCase();
System.out.println(toUpper.apply("stanley")); // Output: STANLEY
✅ Example 2: Math transformation
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5)); // Output: 25
✅ Common use in List.replaceAll:
List<String> names = new ArrayList<>(List.of("stan", "anna", "bob"));
names.replaceAll(String::toUpperCase);
System.out.println(names); // Output: [STAN, ANNA, BOB]
✅ Summary
| Interface | Input | Output | Notes |
|---|---|---|---|
Function<T, R> | T | R | Generic input/output |
UnaryOperator<T> | T | T | Input and output are same type |