Java8 - Numeric BinaryOperator interface examples | Functional Interfaces tutorials
In this blog post, We are going to learn the Numeric BinaryOperators
class in java8 with examples.
In my previous post, discussed BinaryOperator tutorials with examples
What is Binary Operator?
Binary Operators are operators that take two parameters of primitive type and output the same primitive type values.
Numeric BinaryOperators
are declared in java.util.function
package. Each numeric primitive types like long, int, and double have binary operators.
Java8 has following numeric binary operators
- DoubleBinaryOperator
- IntBinaryOperator
- LongBinaryOperator
DoubleBinaryOperator class in java
It is a functional interface that takes two double values as input and output double values.
It is a double version of BinaryOperator
.
It has a single abstract method - applyAsDouble(T, V)
where T and V are two input parameters and return the result in double.
use 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));
}
}
Output:
35.0
70.0
IntBinaryOperator class in java
It is Integer version of BinaryOperator
defined in java.util.function
. It takes two integer values as input and output integer-only.
It has only one abstract applyAsInt()
method.
Here is an IntBinaryOperator Example
import java.util.function.IntBinaryOperator;
public class Test {
public static void main(String[] args) throws Exception{
IntBinaryOperator sumOperator= (p, q) -> p + q;
System.out.println(sumOperator.applyAsInt(35, 41));
}
}
Output:
76
LongBinaryOperator class in java
It is a long version of BinaryOperator
defined in java.util.function
. This is an operation that takes two long values as input and produces an output of long. It has only one abstract applyAsLong()
method.
Following is a LongBinaryOperator Example
LongBinaryOperator sumOperator= (p, q) -> p + q;
System.out.println(sumOperator.applyAsLong(15, 25));
The output of the above code execution is
40
Conclusion
In this post, Learned Numeric BinaryOperators with examples