BinaryOperator Interface in Java 8 with examples

This entry is part 6 of 43 in the series Java 8 Functional Interfaces

BinaryOperator 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 two input arguments of same type as input but produces the output of same type as input arguments. In this post, we are going to see several implementations of BinaryOperator Interface by using different examples.

Also, BinaryOperator extends BiFunction interface therefore, it inherits apply() and andThen() functional methods from  the BiFunction.

BinaryOperator_Interface_Java8_Techndeck

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

Look at BinaryOperator Javadoc description below:

BinaryOperatorInterface_Signature_Java8_Techndeck

 

 

 

 

 

BinaryOperator Interface contains 2 methods of it’s own and 2 extended methods:

  1. minBy

  2. maxBy

  3. apply (extended from BiFunction)

  4. andThen (extended from BiFunction)

 

Let’s discuss these methods:

minBy

This method returns a BinaryOperator which returns the lesser of two elements according to the specified Comparator.

maxBy

This method returns a BinaryOperator which returns the greater of two elements according to the specified Comparator.

apply 

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

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. ‘minBy’

Output:

 

Example 4. ‘maxBy’

Output:

 

Java 8 BinaryOperator 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.

 

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

 

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

Other Useful References:

 

Series Navigation<< DoubleBinaryOperator Interface in Java 8 with examplesObjLongConsumer Interface in Java 8 with examples >>

Leave a Reply

Your email address will not be published.Required fields are marked *

Facebook Twitter Instagram YouTube