How to implement LongBinaryOperator using lambda and method reference in Java?


LongBinaryOperator is a part of the functional interface from java.util.function package. This functional interface expects two parameters of type long as the input and produces a long type result. LongBinaryOperator interface can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method, applyAsLong().

Syntax

@FunctionalInterface
public interface LongBinaryOperator {
 long applyAsLong(long left, long right)
}

Example of Lambda Expression

import java.util.function.LongBinaryOperator;
public class LongBinaryOperatorTest1 {
   public static void main(String[] args) {
      LongBinaryOperator multiply = (a,b) -> { // lambda expression
         return a*b;
      };
      long a = 10;
      long b = 20;
      long result = multiply.applyAsLong(a,b);
      System.out.println("Multiplication of a and b: " + result);
      a = 20;
      b = 30;
      System.out.println("Multiplication of a and b: " + multiply.applyAsLong(a,b));
      a = 30;
      b = 40;
      System.out.println("Multiplication of a and b: " + multiply.applyAsLong(a,b));
   }
}

Output

Multiplication of a and b: 200
Multiplication of a and b: 600
Multiplication of a and b: 1200


Example of Method Reference

import java.util.function.LongBinaryOperator;
public class LongBinaryOperatorTest2 {
   public static void main(String[] args) {
      LongBinaryOperatorTest2 instance = new LongBinaryOperatorTest2();
      LongBinaryOperator test = instance::print;     // method reference
      System.out.println("The sum of l1 and l2: " + test.applyAsLong(50, 70));
   }
   long print(long l1, long l2) {
      return l1+l2;
   }
}

Output

The sum of l1 and l2: 120

Updated on: 14-Jul-2020

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements