In this lesson, we will explore another Functional interface introduced in Java 8, part of the java.util.function package. It is a UnaryOperator interface.
UnaryOperator interface extends the Function interface, which we covered in previous lessons.
In addition to inherited methods from the Function interface, it has one static method of its own.
That is static <T> UnaryOperator<T> identity() that returns a unary operator that always returns its input argument.
UnaryOperator<T>
@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T> { /** * Returns a unary operator that always returns its input argument. * * @param <T> the type of the input and output of the operator * @return a unary operator that always returns its input argument */ static <T> UnaryOperator<T> identity() { return t -> t; } }
Implementing the UnaryOperator interface
Example 1:
Implementation of the static identity() method. This example also illustrates the inherited accept() method from the Function interface.
class Test { public static void main(String[] args) { UnaryOperator<String> unaryOperator = UnaryOperator.identity(); System.out.println(unaryOperator.apply("Hello Java!")); } }
As you can see, the identity() method will return whatever we pass as the parameter to the apply() function.
Example 2:
Implementing the inherited default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) method from the Function interface.
class Test { public static void main(String[] args) { UnaryOperator<Integer> addition = num -> num + 5; UnaryOperator<Integer> subtraction = num -> num - 3; Function<Integer, Integer> result = addition.andThen(subtraction); System.out.println("The result is: " + result.apply(5)); } }
The endThen() method accepts the Function as a parameter, and we passed the UnaryOperator since it extends the Function interface.
As you can see, we can use all the methods from the Function interface plus one additional.
Happy coding!