“This is the seventh day of my participation in the First Challenge 2022.

Writing in the front

The JDK8 API provides a number of functional interfaces that can be abstracted into concrete methods and used in Lambda expressions, including the UnaryOperator function interface.

UnaryOperator for JDK8 functional interface

The UnaryOperator function interface is a computational function. Let’s take a look at the source code first.

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

    static <T> UnaryOperator<T> identity(a) {
        returnt -> t; }}Copy the code

Function<T,T> Function<T,T> Function<T,T> Function<T,T>

This indicates that the apply interface method exists on this interface.

And this interface implements the identity method separately.

Let’s see how this function interface is used in code, as follows:

public static void main(String[] args) {
    UnaryOperator<Integer> operator = x -> x + 1;
    System.out.println(operator.apply(1));
}
Copy the code

The result of executing the code is as follows:

So we can see that when we use the Apply interface method, we add one to the original number according to our own rules.

AndThen method

Function<T,T> = Function<T,T> = Function<T,T> = Function<T,T>

public static void main(String[] args) {
    UnaryOperator<Integer> operator = x -> x + 1;
    UnaryOperator<Integer> operator1 = x -> x + 10;
    System.out.println(operator.andThen(operator1).apply(1));
}
Copy the code

The result of executing the code is as follows:

As you can see from the above approach, the UnaryOperator interface is basically just an operator, as the name implies.

So it’s easier to understand the interface in terms of operators.

conclusion

Today we looked at the UnaryOperator functional interface. We showed examples of how operators are used in functional programming, as well as other operator interfaces, which we will cover in the following sections.