Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Functional Interfaces – UnaryOperator & BinaryOperator

Java Functional InterfacesUnaryOperator & BinaryOperator

This section describes the functional interfaces UnaryOperator and BinaryOperator defined in java.util.Function package in Java 8.

What is it?

 UnaryOperator: A functional interface that represents an operation that accepts one argument and returns a result of same type as the argument.  

@FunctionalInterface

public interface UnaryOperator<T> extends Function<T,T>

.

There are three primitive unary operators for Integer, Long and Double – IntUnaryOperator, LongUnaryOperator and DoubleUnaryOperator – that accept corresponding value types and return same value types.

.

 BinaryOperator: A functional interface that represents an operation that accepts two arguments of the same type, and returns a result of the same type as the arguments.

@FunctionalInterface

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

.

There are three primitive unary operators for Integer, Long and Double – IntBinaryOperator, LongBinaryOperator and DoubleBinaryOperator – that accept corresponding value types and return same value types.

.

The BinaryOperator interface consists of following functions:

1.maxBy() – Returns a BinaryOperator which returns the greater of two elements based on the specified comparator.
2.minBy() – Returns a BinaryOperator which returns the lesser of two elements based on the specified comparator.

.

Why it was introduced?

.

 UnaryOperator and BinaryOperator are introduced as specializations of the Function and BiFunction interfaces, respectively, with the argument(s) and the return value being of the same type.

.

Examples

.

The examples illustrated below use the following Employee POJO class:

.

package org.examples;

.

public class Employee {

      private String name;

      private Integer hourRate;

      public String getName() {

        return name;

      }

      public void setName(String name) {

        this.name = name;

      }

      public Integer getHourRate() {

        return hourRate;

      }

      public void setHourRate(Integer hourRate) {

        this.hourRate = hourRate;

      }

      public Employee(String name, Integer hourRate) {

        super();

        this.name = name;

        this.hourRate = hourRate;

      }

      

}

.

.

 UnaryOperator

.

1.This implementation shows usage of IntUnaryOperator to calculate dailyRate from the hourRate of the employees in a list of Employee objects.

.

package org.examples;

.

import java.util.ArrayList;

import java.util.List;

import java.util.function.IntUnaryOperator;

.

public class UnaryExample1 {

public static void main(String[] args)

  {

.

    List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));      

.

         employees.forEach(emp ->

       System.out.println(getDailyRateFunc().applyAsInt(emp.getHourRate())));

  }

.

  public static IntUnaryOperator getDailyRateFunc()

  {

    return hourRate -> hourRate * 8;

  }

}

Output:

80

400

240

160

.

.

.

.

.

.

.

.

.

2.This implementation doubles the hourRate of each employee in a list of Employee objects.

.

.

.

.

.

.

.

3.This implementation shows chaining of two UnaryOperator functions using andThen() and apply() methods. It changes the case and prepending with salutation the names of employees in a list of Employee objects.

.

package org.examples;

.

import java.util.ArrayList;

import java.util.List;

import java.util.function.UnaryOperator;

.

public class UnaryExample2 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));    

    

    List<Employee> newRateEmployees =

                           changeRate(employees, getIncrementRateFunction());              

    newRateEmployees.forEach(employee ->

                                       System.out.println(employee.getHourRate()));

}

  

  public static UnaryOperator<Employee> getIncrementRateFunction()

  {

    UnaryOperator<Employee> incrementRate = emp ->

    {

      emp.setHourRate(emp.getHourRate()*2);

      return emp;

    };

    return incrementRate;

  }    

.

  public static List<Employee>

          changeRate(List<Employee> employeeList, UnaryOperator<Employee> unaryFunc)

  {

    List<Employee> newRateEmployees = new ArrayList<>();

    employeeList.forEach(emp ->

                                       newRateEmployees.add(unaryFunc.apply(emp)));

    return newRateEmployees;  

       }

}

Output:

20

100

60

40

package org.examples;

.

import java.util.ArrayList;

import java.util.List;

import java.util.function.UnaryOperator;

.

public class UnaryExample3 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

          

      List<Employee> newRateEmployees =

modifyName(employees,getChangeCaseFunction(),getAddSalutationFunction());              

    newRateEmployees.forEach(employee ->

                                         System.out.println(employee.getName()));

  

}

    

  public static UnaryOperator<Employee> getChangeCaseFunction()

  {

    UnaryOperator<Employee> changeCase = emp ->

    {

      emp.setName(emp.getName().toUpperCase());

      return emp;

    };

    return changeCase;

  }

  

  public static UnaryOperator<Employee> getAddSalutationFunction()

  {

    UnaryOperator<Employee> addSalutation = emp ->

    {

      emp.setName(“MR. “ + emp.getName());

      return emp;

    };  

    return addSalutation;

  }

    

  public static List<Employee> modifyName(List<Employee> employeeList,

             UnaryOperator<Employee> unaryFunc1, UnaryOperator<Employee> unaryFunc2)

  {

    List<Employee> newEmployeesList = new ArrayList<>();

    employeeList.forEach(emp ->

                    newEmployeesList.add(unaryFunc1.andThen(unaryFunc2).apply(emp)));

    return newEmployeesList;  

       }

}

Output:

MR. JACK

MR. ROBERT

MR. DAVID

MR. ABHI

.

 BinaryOperator

.

1.This implementation shows usage of BinaryOperator to calculate total hourRate of all the employees in a list of Employee objects.

.

package org.examples;

.

import java.util.ArrayList;

import java.util.List;

import java.util.function.BinaryOperator;

.

public class UnaryExample1 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

                        

    Integer result = getTotalRate(employees, getTotalRateFunction());

    System.out.println(result);    

  }

    

  public static BinaryOperator<Integer> getTotalRateFunction()

  {

    return (rate1,rate2) -> rate1 + rate2;

  }  

.

  public static Integer

            getTotalRate(List<Employee> employees, BinaryOperator<Integer> binaryFunc)

  {

    Integer total = 0;

    for(Employee emp : employees)

    {

      total = binaryFunc.apply(total, emp.getHourRate());

    }

    return total;

  }

}

Output:

110

.

.

.

.

.

.

.

.

.

.

.

.

2.This implementation shows usage of minBy() and maxBy() to find the maximum and minimum hourRate in a list of Employee objects.

.

package org.examples;

.

import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

import java.util.function.BinaryOperator;

.

public class BinaryExample3 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

  

    BinaryOperator<Employee> maxOp = BinaryOperator.maxBy(compareRate);

    

Employee maxRateEmp = findEmployee(employees, maxOp);

    System.out.println(“Max rate: “ + maxRateEmp.getHourRate());

    

    BinaryOperator<Employee> minOp = BinaryOperator.minBy(compareRate);

    

Employee minRateEmp = findEmployee(employees, minOp);

    System.out.println(“Min rate: “ + minRateEmp.getHourRate());

  }

  

  public Comparator<Employee> getRateComparator()

  {

    Comparator<Employee> compareRate = new Comparator<Employee>() {

      @Override

      public int compare(Employee o1, Employee o2) {

        return o1.getHourRate().compareTo(o2.getHourRate());

      }

    };

    return compareRate;

  }    

.

  public static Employee

          findEmployee(List<Employee> employees, BinaryOperator<Employee> binaryFunc)

  {

    Employee resultEmp = null;

    for(Employee emp : employees)

    {

      if(resultEmp == null)

        resultEmp = emp;

      else

        resultEmp = binaryFunc.apply(resultEmp, emp);

    }

    return resultEmp;

  }

}

Output:

Max rate: 50

Min rate: 10

.

Leave a Reply

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

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed