BinaryOperator
is a functional interface, which takes in two arguments of the same type and returns a result that is also of the same type. This interface extends the BiFunction interface. This interface has two methods:
minBy(Comparator<? super T> comparator)
maxBy(Comparator<? super T> comparator)
The BinaryOperator
interface is defined in the java.util.function
package. To import the BinaryOperator
interface, we check the following import statement:
import java.util.function.BinaryOperator;
minBy(Comparator<? super T> comparator)
This method returns a BinaryOperator
, which returns the lesser/minimum of the two given inputs, as per the specified Comparator
.
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator)
Comparator<? super T> comparator
: This is the comparator that is used to compare the inputs.This method returns a BinaryOperator
.
import java.util.Comparator;import java.util.function.BinaryOperator;public class Main{public static void main(String[] args) {// Comparator for the comparison of the input argumentsComparator<Integer> integerComparator = Comparator.naturalOrder();// BinaryOperator to get the minimum of the input argumentsBinaryOperator<Integer> integerIntegerBinaryOperator = BinaryOperator.minBy(integerComparator);// first argumentint arg1 = 2;// second argumentint arg2 = 4;// Test the argumentsSystem.out.printf("minimum(%s, %s) = %s", arg1, arg2, integerIntegerBinaryOperator.apply(arg1, arg2));}}
Comparator
for the comparison of the input arguments.BinaryOperator
to get the minimum of the input arguments.minBy()
method of the BinaryOperator
, using the apply
method on the arguments defined in lines 15 and 18.maxBy(Comparator<? super T> comparator)
This method returns a BinaryOperator
, which returns the greater/maximum of the two given inputs, as per the specified Comparator
.
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator)
Comparator<? super T> comparator
: This is the comparator that is used to compare the inputs.This method returns a BinaryOperator
.
import java.util.Comparator;import java.util.function.BinaryOperator;public class Main{public static void main(String[] args) {// Comparator for the comparison of the input argumentsComparator<Integer> integerComparator = Comparator.naturalOrder();// BinaryOperator to get the maximum of the input argumentsBinaryOperator<Integer> integerIntegerBinaryOperator = BinaryOperator.maxBy(integerComparator);// first argumentint arg1 = 2;// second argumentint arg2 = 4;// Test the argumentsSystem.out.printf("maximum(%s, %s) = %s", arg1, arg2, integerIntegerBinaryOperator.apply(arg1, arg2));}}
Comparator
for the comparison of the input arguments.BinaryOperator
to get the maximum of the input arguments, using the maxBy()
method.maxBy()
method of the BinaryOperator
, using the apply
method on the arguments defined in lines 15 and 18.