The UnaryOperator Interface in Java
In Java, the UnaryOperator
interface is a functional interface that represents an operation on a single operand that produces a result of the same type as its operand. It is part of the java.util.function
package and is used to perform various operations on values.
Here is the definition of the UnaryOperator
interface:
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
The UnaryOperator
interface extends the Function
interface and has a single abstract method, apply()
, which takes an argument of type T
and returns a value of type T
. The T
type is a type parameter that specifies the type of the operand and the result of the operation.
The UnaryOperator
interface also provides a static method, identity()
, which returns a unary operator that always returns its input argument.
Here is an example of how to use the UnaryOperator
interface:
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(3)); // prints 9
System.out.println(square.apply(5)); // prints 25
In this example, we define a unary operator, square
, that computes the square of an integer value. We then use the apply()
method of the square
operator to compute the squares of various integer values.
The UnaryOperator
interface is similar to the Function
interface, but it is more restricted in that it can only operate on values of a single type. This makes it easier to use in certain situations, as you don't have to specify the types of the operand and result separately.