UnaryOperator<T> is a functional interface that extends the Function interface. It represents an operation that accepts a parameter and returns a result of the same type as its input parameter. The apply() method from Function interface and default methods: andThen() and compose() are inherited from the UnaryOperator interface. A lambda expression and method reference can use UnaryOperator objects as their target.
@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T>
import java.util.function.UnaryOperator; public class UnaryOperatorTest1 { public static void main(String[] args) { UnaryOperator<Integer> operator = t -> t * 2; // lambda expression System.out.println(operator.apply(5)); System.out.println(operator.apply(7)); System.out.println(operator.apply(12)); } }
10 14 24
import java.util.function.UnaryOperator; public class UnaryOperatorTest2 { public static void main(String[] args) { UnaryOperator<Integer> operator1 = t -> t + 5; UnaryOperator<Integer> operator2 = t -> t * 5; // Using andThen() method int a = operator1.andThen(operator2).apply(5); System.out.println(a); // Using compose() method int b = operator1.compose(operator2).apply(5); System.out.println(b); } }
50 30