Java 8 UnaryOperator Interface

7 years ago Lalit Bhagtani 0

In this tutorial, we will learn about Java 8 UnaryOperator interface.

Java 8 UnaryOperator Interface

UnaryOperator Interface :-

UnaryOperator ( java.util.function.UnaryOperator ) is a subinterface of the Function interface, it has one static method along with all the abstract and default method inherited from the Function interface. It represents an algorithm where input parameter of one type is used to produce return value of same type. This interface is a specialized form of Function interface for the case where passed argument and return value are of same type. 

Static method :- 

static <T> UnaryOperator<T> identity() :- It returns a UnaryOperator that always returns its input argument.

Reference :-  UnaryOperator Interface JavaDocs 

Java 8 Stream API have one method where UnaryOperator interface is used as an argument :- 

static <T> Stream<T> iterate( T seed, UnaryOperator<T> f )

There are three specialized ( primitive specific ) form of Java 8 UnaryOperator interface, which can be used in case of int, long and double. They are as follows :-

  1. IntUnaryOperator interface ( JavaDocs ) :- It represents a UnaryOperator that accepts one integer value as an argument and returns an integer value.
  2. DoubleUnaryOperator interface ( JavaDocs ) :- It represents a UnaryOperator that accepts one double value as an argument and returns a double value.
  3. LongUnaryOperator interface ( JavaDocs ) :- It represents a UnaryOperator that accepts one long value as an argument and returns a long value.

Example – 1 :- 

This example will show you, how to create and call identity method of an UnaryOperator interface.

  public static void main(String[] args){
 
    UnaryOperator<Integer> uOpertor1 = ( t ) -> { return 2 * t * t; };
 
    // apply method Example
    int output = uOpertor1.apply(2);
    System.out.println(output);
 
    // identity method Example
    UnaryOperator<Integer> uOperator2 = UnaryOperator.identity();
    int output2 = uOperator2.apply(2); 
    System.out.println(output2); 
 
 }

Result :- 

8
2

Example – 2 :- 

In this example, we will generate new stream by using stream’s iterate() method. This method takes one UnaryOperator as an argument.

  public static void main(String[] args){
 
    UnaryOperator<Integer> uOpertor = ( t ) -> 2 * t;
 
    Stream<Integer> stream = Stream.iterate(1, uOpertor).limit(5);
    stream.forEach(System.out::println);
 
 }

Result :- 

1
2
4
8
16

That’s all for Java 8 UnaryOperator Interface. If you liked it, please share your thoughts in comments section and share it with others too.