What is the UnaryOperator functional interface in Java?
Overview
UnaryOperator is a functional interface that represents a single-operand operation which yields a result of the same type as the operand.
The interface extends the Function interface so the methods of the Function interface can be used on the implementation of the UnaryOperator interface. The interface overrides the identity() method of the Function interface.
The UnaryOperator interface is defined in the java.util.function package. To import the UnaryOperator interface, use the following import statement:
import java.util.function.UnaryOperator;
What is the identity() method?
The identity() method is a static method used to return a unaryOperator that always returns its input argument.
Syntax
static <T> UnaryOperator<T> identity()
Parameters
The method has no parameters.
Return value
This method returns the input argument.
Example
import java.util.function.UnaryOperator;public class Main{public static void main(String[] args) {// Identity unary operator that accepts one inputUnaryOperator<Integer> unaryOperator = UnaryOperator.identity();// argumentint arg = 3;System.out.printf("UnaryOperator.identity(%s) = %s", arg, unaryOperator.apply(3));}}
Explanation
- Line 1: We import the relevant packages.
- Line 8: We define an identity
unaryOperatorthat accepts one input of integer type. - Line 11: We define an integer value.
- Line 13: We test the identity
unaryOperatorusing theapply()method on the integer value defined in line 11 and print the result.