UnaryOperator Interface

Lambda

UnaryOperator Interface


The UnaryOperator is a built-in functional interface included in Java SE 8 in the java.util.function package, that extends java.util.function.Function. It is used to work on a single operand and it returns the same type as an operand. The UnaryOperator is used as a lambda expression to pass as an argument.

Example 1. java.util.function.UnaryOperator Interface

The definition of the interface is shown in the example:

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
    ...
}

Function descriptor of the interface is:

T -> T

Example 2. Usage of java.util.function.UnaryOperator Interface

Let's look at the simple example:

UnaryOperator<String> uo = s -> s.toUpperCase();
System.out.print(uo.apply("Ocpjp 8"));

This example can be rewritten with method reference:

UnaryOperator<String> uo = String::toUpperCase;
System.out.print(uo.apply("Ocpjp 8"));

Th UnaryOperator interface inherits the default methods of the Function interface:

default <V> Function<V,R> compose(
         Function<? super V,? extends T> before)
default <V> Function<T,V> andThen(
         Function<? super R,? extends V> after)

And defines the static method identity() for the interface:

static <T> UnaryOperator<T> identity()

 



0 comments
Leave your comment: