Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

UnaryOperator

A function whose argument and result have the same type.

Available since: Java 8

Syntax

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T>

Examples

A chain of string transformations:

void main() {
    UnaryOperator<String> trim = String::trim;
    UnaryOperator<String> upper = String::toUpperCase;
    IO.println(trim.andThen(upper).apply("  hello  "));
}

Output:

HELLO

Notes

It is a special case of Function<T, T>. It is taken by List.replaceAll() and Stream.iterate(). Note that andThen() returns a Function, not a UnaryOperator.

See also

  • Function — A function that takes a value of type `T` and returns a value of type `R`.
  • BinaryOperator — A two-argument function whose arguments and result share a type.
  • List.replaceAll() — Replaces every list element with the result of a function.
  • Stream.iterate() — Creates a stream where each element is computed from the previous one.

In the tutorial

  • Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.

Thanks for reading!

Donate to the site — we work hard for you.