Saturday, August 18, 2018

Java8 - Numeric BinaryOperator interface examples | Functional Interfaces tutorials

In my previous post, discussed BinaryOperator tutorials with examples
Numeric BinaryOperators are declared in java.util.function package. Each numeric primitive types like long, int and double have binary operators. Binary Operators are operators that take two parameters of primitive type and outputs the same primitive type values


It is a functional interface that takes two double values as input and output double value. It is a double version of BinaryOperator. It has a single abstract method - applyAsDouble(T, V) T and V are two input parameters and return the result of double.

Lambda Expression and Method reference example 

The below code showcase the usage of DoubleBinaryOperator with lambda/Method reference

package org.cloudhadoop.functions;
import java.util.function.DoubleBinaryOperator;
public class MyDoubleBinaryOperatorExample {
	public static double mutiply(double d1, double d2) {
		return d1 * d2;
	public static void main(String[] args) {

		// Using Lambda Expression
		DoubleBinaryOperator lamdaExample = (v1, v2) -> MyDoubleBinaryOperatorExample.mutiply(v1, v2);
		System.out.println(lamdaExample.applyAsDouble(5, 7));
		// Using Method reference
		DoubleBinaryOperator methodRefExample = MyDoubleBinaryOperatorExample::mutiply;
		System.out.println(methodRefExample.applyAsDouble(35, 2));


It is Integer version of BinaryOperator defined in java.util.function, which takes two integer values as input and output integer-only. It has only one abstract applyAsInt() method.


IntBinaryOperator sumOperator= (p, q) -> p + q;
System.out.println(sumOperator.applyAsInt(35, 41));
Output is


It is a long version of BinaryOperator defined in java.util.function. This is an operation takes two long values as input and produces an output of long. It has only one abstract applyAsLong() method.


LongBinaryOperator sumOperator= (p, q) -> p + q;
		System.out.println(sumOperator.applyAsLong(15, 25));
The output of the above code execution is

Related article