Open In App

BinaryOperator Interface in Java

Improve
Improve
Like Article
Like
Save
Share
Report

The BinaryOperator Interface<T> is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a binary operator which takes two operands and operates on them to produce a result. However, what distinguishes it from a normal BiFunciton is that both of its arguments and its return type are same.

This functional interface which takes in one generic namely:- 

  • T: denotes the type of the input arguments and the return value of the operation

The BinaryOperator<T> extends the BiFunction<T, T, T> type. So it inherits the following methods from the BiFunction Interface:  

The lambda expression assigned to an object of BiaryOperator type is used to define its apply() which eventually applies the given operation on its arguments.  

Functions in BinaryOperator Interface

The BinaryOperator interface consists of the following functions: 

1. maxBy()

This methods return a BinaryOperator which returns the greater of the two elements based on a given comparator

Syntax:  

static <T> BinaryOperator<T> 
    maxBy(Comparator<? super T> comparator)

Parameters: It takes in only one parameter namely, comparator which is an object of the Comparator class.

Returns: This method returns a BinaryOperator which returns the maximum of the two objects passed while calling it based on the given comparator.

Below is the code to illustrate maxBy() method:

Program:  

Java




import java.util.function.BinaryOperator;
 
public class GFG {
    public static void main(String args[])
    {
        BinaryOperator<Integer>
            op = BinaryOperator
                     .maxBy(
                         (a, b) -> (a > b) ? 1 : ((a == b) ? 0 : -1));
 
        System.out.println(op.apply(98, 11));
    }
}


Output: 

98

 

2. minBy()

This method returns a BinaryOperator which returns the lesser of the two elements based on a given comparator

Syntax: 

static <T> BinaryOperator<T> 
    minBy(Comparator<? super T> comparator)

Parameters: It takes in only one parameter namely, comparator which is an object of the Comparator class.

Returns: This method returns a BinaryOperator which return the minimum of the two objects passed while calling it based on the given comparator.

Below is the code to illustrate minBy() method:

Program

Java




import java.util.function.BinaryOperator;
 
public class GFG {
    public static void main(String args[])
    {
        BinaryOperator<Integer>
            op = BinaryOperator
                     .minBy(
                         (a, b) -> (a > b) ? 1 : ((a == b) ? 0 : -1));
 
        System.out.println(op.apply(98, 11));
    }
}


Output: 

11

 



Last Updated : 30 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads