Binary operators in java8 with code examples

Introduction

BinaryOperator was introduced in java 8 as part of java.util.function. It accepts 2 arguments as inputs and returns an output.It was introduced to implement functional programming in java.

JavaDoc:

Type Parameters:
T - the type of the operands and result of the operator
All Superinterfaces:
BiFunction<T,T,T>
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Functions of BinaryOperator interface:

BinaryOperator is very similar to Bi-Function except that it enforces the operands to be of same type and also the result to be also of the same type.

  • andThen
  • apply
  • MaxBy
  • MinBy

Code example for apply BinaryOperator:

In the below code example, I have create a a binaryOperator addFunc which takes 2 integers as input and returns an integer as output.

package com.codingbrains.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.BinaryOperator;
public class BinaryOperatorEx {
  public static void main(String[] args) {
    BinaryOperator<Integer> addFunc=(a,b)->a+b;
    System.out.println(addFunc.apply(2,4));
  }
}

You may also like...

Leave a Reply

Your email address will not be published.