BinaryOperator.minBy and maxBy: Comparator-Based Selection
What You'll Learn
You'll learn how to use BinaryOperator's static factory methods minBy and maxBy to create operators that select the smaller or larger of two values based on a Comparator.
The Core Idea
While BinaryOperator<T> represents any operation that takes two values of type T and returns a value of type T, sometimes you specifically want to pick the winner between two values. The minBy and maxBy static methods create BinaryOperator instances that compare two values and return the one that's considered "smaller" or "larger" according to a provided Comparator.
Think of it like a tournament referee: given two competitors and a rulebook (the Comparator), minBy picks the lower-ranked one, while maxBy picks the higher-ranked one.
Method Signatures
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator)
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator)
Basic Usage
BinaryOperator<Integer> min = BinaryOperator.minBy(Integer::compareTo);
BinaryOperator<Integer> max = BinaryOperator.maxBy(Integer::compareTo);
Integer smaller = min.apply(5, 10); // returns 5
Integer larger = max.apply(5, 10); // returns 10
Practical Example with Custom Objects
BinaryOperator<String> shortest = BinaryOperator.minBy(
Comparator.comparingInt(String::length)
);
BinaryOperator<String> longest = BinaryOperator.maxBy(
Comparator.comparingInt(String::length)
);
String short = shortest.apply("cat", "elephant"); // "cat"
String long = longest.apply("cat", "elephant"); // "elephant"
These operators are particularly useful in reduction operations where you need to find the minimum or maximum value in a stream.
Key Takeaway: BinaryOperator.minBy and maxBy create selection operators that compare two values using a Comparator and return the smaller or larger one, respectively—perfect for finding extremes in data.