Lambda Expressions · Lesson 9/9
100%
⏱ 10–15 min

Functional Interface UnaryOperator

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("Java Core"));

This example can be rewritten with a method reference:

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

The 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()

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. OOP Basics
9. Lambda Expressions
10. Stream API
11. Inner Classes and Exceptions
12. Git & GitHub
‹ Previous lesson Next lesson ›