The BinaryOperator interface in Java is a functional interface that extends the BiFunction interface. It takes two arguments of the same type and produces a result of the same type. It is typically used for functional-style operations where two operands of the same type need to be combined into one result.
Key Details about BinaryOperator:
- Located in the
java.util.functionpackage. - It is a generic interface (
BinaryOperator<T>), whereTis the type of input arguments and the return type. - It comes with useful static methods like
minBy()andmaxBy()to create comparators.
Functional Method
The BinaryOperator interface declares the following functional method:
T apply(T t1, T t2);
This method applies the operation to the given arguments and returns the result.
Example Usage of the BinaryOperator Interface
Sum of Two Integers:
We can use BinaryOperator to perform simple addition:
package org.kodejava.util.function;
import java.util.function.BinaryOperator;
public class SumOfTwoIntegers {
public static void main(String[] args) {
BinaryOperator<Integer> add = (a, b) -> a + b;
// Output: 30
System.out.println("Sum: " + add.apply(10, 20));
}
}
Find Maximum or Minimum Using Comparators
Using BinaryOperator.maxBy() and BinaryOperator.minBy(), we can determine the maximum or minimum value based on a given comparator:
package org.kodejava.util.function;
import java.util.function.BinaryOperator;
import java.util.Comparator;
public class MaxMinComparator {
public static void main(String[] args) {
BinaryOperator<Integer> maxOperator =
BinaryOperator.maxBy(Comparator.naturalOrder());
BinaryOperator<Integer> minOperator =
BinaryOperator.minBy(Comparator.naturalOrder());
// Output: 20
System.out.println("Max: " + maxOperator.apply(10, 20));
// Output: 10
System.out.println("Min: " + minOperator.apply(10, 20));
}
}
String Concatenation:
BinaryOperator can also work with strings or other types:
package org.kodejava.util.function;
import java.util.function.BinaryOperator;
public class ConcatenateString {
public static void main(String[] args) {
BinaryOperator<String> concat =
(str1, str2) -> str1 + str2;
// Output: Hello, World!
System.out.println("Concatenated String: " +
concat.apply("Hello, ", "World!"));
}
}
Common Use Cases:
- Arithmetic operations (e.g., add, subtract, multiply, divide).
- Aggregation functions (e.g., finding the maximum, minimum, or average of elements).
- Combining elements in functional streams.
- Handling data transformations using custom logic.
Integrating with Streams:
BinaryOperator is often used in reduce() operations of a Stream:
package org.kodejava.util.function;
import java.util.stream.Stream;
import java.util.function.BinaryOperator;
public class BinaryOperatorInStream {
public static void main(String[] args) {
BinaryOperator<Integer> add = Integer::sum;
// Reduce the stream with addition
Integer sum = Stream.of(1, 2, 3, 4, 5)
.reduce(0, add);
// Output: 15
System.out.println("Total: " + sum);
}
}
