How to use UnaryOperator<T> interface in lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

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.

Syntax

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T>

Example-1

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));
   }
}

Output

10
14
24

Example-2

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);
   }
}

Output

50
30
raja
Published on 02-Jan-2020 13:18:17
Advertisements