How to implement IntBinaryOperator using lambda expression in Java?


IntBinaryOperator is a functional interface in Java 8 from java.util.function package. This interface expects two parameters of type int as input and produces an int type result. IntBinaryOperator can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method: applyAsInt().

Syntax

@FunctionalInterface
public interface IntBinaryOperator {
 int applyAsInt(int left, int right)
}

Example

import java.util.function.*;
public class IntBinaryOperatorTest {
   public static void main(String[] args) {
      IntBinaryOperator test1 = (a, b) -> a + b; // lambda expression
      System.out.println("Addition of two parameters: " + test1.applyAsInt(10, 20));
      IntFunction test2 = new IntFunction() {
         @Override
         public IntBinaryOperator apply(int value) {
            return new IntBinaryOperator() {
               @Override
               public int applyAsInt(int left, int right) {
                  return value * left * right;
               }
            };
         }
      };
      System.out.println("Multiplication of three parameters: " + test2.apply(10).applyAsInt(20, 30));
   }
}

Output

Addition of two parameters: 30
Multiplication of three parameters: 6000

Updated on: 14-Jul-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements