BinaryOperator Interface in Java


The BinaryOperator interface represents an operation upon two operands of the same type, producing a result of the same type as the operands.

Following are the methods −

Modifier and TypeMethod and Description
maxBy(Comparator<? super T> comparator)Returns a BinaryOperator which returns the greater of two elements according to the specified Comparator.
minBy(Comparator<? super T> comparator)Returns a BinaryOperator which returns the lesser of two elements according to the specified Comparator.

Example

Let us now see an example −

 Live Demo

import java.util.function.BinaryOperator;
public class Demo {
   public static void main(String args[])   {
      BinaryOperator<Integer>
      operator = BinaryOperator
      .maxBy(
      (x, y) -> (x > y) ? 1 : ((x == y) ? 0 : -1));
      System.out.println(operator.apply(120, 5));
   }
}

Output

This will produce the following output −

120

Example

Let us now see another example −

 Live Demo

import java.util.function.BinaryOperator;
public class Demo {
   public static void main(String args[]) {
      BinaryOperator<Integer> operator = (x, y) -> x * y;
      System.out.println(operator.apply(5, 7));
   }
}

Output

This will produce the following output −

35

Updated on: 02-Jan-2020

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements