src/share/classes/java/util/function/BinaryOperator.java
Print this page
rev 7485 : 8009736: Comparator API cleanup
Reviewed-by:
Contributed-by: henry.jen@oracle.com
@@ -22,10 +22,13 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.function;
+import java.util.Objects;
+import java.util.Comparator;
+
/**
* An operation upon two operands yielding a result. This is a specialization of
* {@code BiFunction} where the operands and the result are all of the same type.
*
* @param <T> the type of operands to {@code apply} and of the result
@@ -33,6 +36,31 @@
* @see BiFunction
* @since 1.8
*/
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
+ /**
+ * Constructs a {@link BinaryOperator} which returns the lesser of two elements
+ * according to the specified {@code Comparator}
+ *
+ * @param comparator A {@code Comparator} for comparing the two values
+ * @return a {@code BinaryOperator} which returns the lesser of its operands,
+ * according to the supplied {@code Comparator}
+ */
+ public static<T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
+ Objects.requireNonNull(comparator);
+ return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
+ }
+
+ /**
+ * Constructs a {@link BinaryOperator} which returns the greater of two elements
+ * according to the specified {@code Comparator}
+ *
+ * @param comparator A {@code Comparator} for comparing the two values
+ * @return a {@code BinaryOperator} which returns the greater of its operands,
+ * according to the supplied {@code Comparator}
+ */
+ public static<T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
+ Objects.requireNonNull(comparator);
+ return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
+ }
}