What Are UnaryOperator And BinaryOperator?
1 min readUnary and Binary operators are the other two functional interfaces that most developers are interested in.
There are two other functional interfaces in Java that represent operations that take one or two operands respectively, and produce a result of the same type as the operands.
Other functional interfaces commonly used
These interfaces are used by developers on a day to day, which are:
- UnaryOperator
- BinaryOperator
UnaryOperator
UnaryOperator is a functional interface and it extends Function.
UnaryOperator is a functional interface that takes a single operand of a specified type, and returns a result of the same type.
This interface extends the Function interface so the methods of the Function the interface can be used in the implementation of the UnaryOperator interface.
The UnaryOperator interface is defined in the java.util.function package.
Syntax
@FunctionalInterface
public interface UnaryOperator<T> {
T apply(T t);
}
For example, you can create a UnaryOperator that doubles an integer value like this:
import java.util.function.UnaryOperator;
import src.dev.ggorantala.constants.Constants;
public class UnaryOperatorExample {
public static void main(String[] args) {
UnaryOperator<Integer> doubleOperator = x -> x * 2;
int result = doubleOperator.apply(Constants.VALUE); // result will be 10
System.out.println(result); // 10
}
}BinaryOperator
BinaryOperator is also a functional interface and it extends BiFunction.
BinaryOperator is a functional interface that takes two operands of a specified type, and returns a result of the same type.
Syntax:
@FunctionalInterface
public interface BinaryOperator<T> {
T apply(T t1, T t2);
}
For example, you can create a BinaryOperator that adds two integers like this:
import java.util.function.BinaryOperator;
import src.dev.ggorantala.constants.Constants;
public class BinaryOperatorExample {
public static void main(String[] args) {
BinaryOperator<Integer> addOperator = Integer::sum;
int result =
addOperator.apply(
Constants.INTEGER_FIRST_VALUE, Constants.INTEGER_SECOND_VALUE); // result will be 5
System.out.println(result); // 5
}
}Both UnaryOperator and BinaryOperator are useful when you want to pass a function as an argument to another method, or when you want to create a lambda expression that can be reused in multiple places.