UnaryOperator Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expects an argument as input but produces the output of same type as input argument. In this post, we are going to see several implementations of UnaryOperator Interface by using different examples.

Also, UnaryOperator extends Function interface therefore, it inherits apply(), compose() and andThen() functional methods from the Function.

UnaryOperator_Interface_Java8_Techndeck

UnaryOperator Interface in Java 8 with Examples...!!! Click To Tweet

Look at UnaryOperator Javadoc description below:

C:\Users\isha\Documents\Techndeck Content\Website Images\UnaryOperatorInterface_Signature_Java8_Techndeck.png

 

 

 

 

 

UnaryOperator Interface contains 1 method of it’s own and 3 extended methods:

  1. identity

  2. apply (extended from Function)

  3. compose (extended from Function)

  4. andThen (extended from Function)

 

Let’s discuss these methods:

identity

This method returns a unary operator that always returns its input argument.

apply 

This method performs operation on the given argument and return the function result.

Compose

This method returns a composed function that first applies the before function to its input, and then applies this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.

andThen

This method returns a composed function that first applies this function to its input, and then applies the after function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.

 

Below are the several examples to demonstrate above methods:

Example 1. ‘apply’

Output:

 

Example 2. ‘andThen’

Output:

 

Example 3. ‘compose’

Output:

 

Java 8 UnaryOperator Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.

 

UnaryOperator Interface in Java 8 with Examples...!!! Click To Tweet

 

Do you like this Post? – then check my other helpful posts:

Other Useful References: