How to use BinaryOperator interface in lambda expression in Java?


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.

Syntax

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

Example

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 : 
"+ 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 :
"+ minPerson);    } } // Person class class Person {    public String name;    public Integer age;    public Person(String name, Integer age) {       this.name = name;       this.age = age;    }    @Override    public String toString(){       return "Name : "+name+", Age : "+age;    } }

Output

Person with higher age :
Name : Jai, Age : 29
Person with lower age :
Name : Adithya, Age : 23

Updated on: 13-Jul-2020

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements