How to use BinaryOperator<T> interface in lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

BinaryOperator<T> is one of a functional interface from java.util.function package and having exactly one abstract method. A lambda expression or method reference uses BinaryOperator objects as their target. BinaryOperator<T> interface represents a function that takes one argument of type T and returns a value of the same type.

BinaryOperator<T> Interface contains two static methods, minBy() and maxBy(). The minBy() method returns a BinaryOperator that returns the greater of two elements according to a specified Comparator while the maxBy() method returns a BinaryOperator that returns the lesser of two elements according to a specified Comparator.


public interface BinaryOperator<T> extends BiFunction<T, T, T>


import java.util.function.BinaryOperator;

public class BinaryOperatorTest {
   public static void main(String[] args) {
      BinaryOperator<Person> getMax = BinaryOperator.maxBy((Person p1, Person p2) -> p1.age-p2.age);

      Person person1 = new Person("Adithya", 23);
      Person person2 = new Person("Jai", 29);
      Person maxPerson = getMax.apply(person1, person2);
      System.out.println("Person with higher age : \n"+ maxPerson);

      BinaryOperator<Person> getMin = BinaryOperator.minBy((Person p1, Person p2) -> p1.age-p2.age);
      Person minPerson = getMin.apply(person1, person2);
      System.out.println("Person with lower age : \n"+ minPerson);

// Person class
class Person {
   public String name;
   public Integer age;
   public Person(String name, Integer age) { = name;
      this.age = age;
   public String toString(){
      return "Name : "+name+", Age : "+age;


Person with higher age :
Name : Jai, Age : 29
Person with lower age :
Name : Adithya, Age : 23
Published on 02-Jan-2020 11:54:30