1.BinaryOperator的定义
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> {
return comparator.compare(a, b) <= 0 ? a : b;
};
}
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> {
return comparator.compare(a, b) >= 0 ? a : b;
};
}
}
- 从上面不难发现,BinaryOperator继承了BiFunction,并且多了二个静态方法minBy和maxBy。
- minBy和maxBy有很意思,返回了一个BiFunction对应的Lambda,Lambda内部使用传入的comparator比较器比较,然后在进一步处理返回最大值还是最小值。
2.更多例子
public class BinaryOperatorTest {
public static void main(String[] args){
BinaryOperatorTest test = new BinaryOperatorTest();
test.testBinaryOperator(1,2,(num1,num2)->num1 + num2);
test.testBinaryOperator(4,2,(num1,num2)->num1 - num2);
test.testBinaryOperator(3,2,(num1,num2)->num1 * num2);
test.testBinaryOperator(8,2,(num1,num2)->num1 / num2);
test.testMinBy("hello","wonders",(str1,str2)->str1.length()-str2.length());
test.testMinBy("hello","wonders", Comparator.comparingInt(String::length));
test.testMinBy("hello","wonders",(str1,str2)->str1.charAt(0)-str2.charAt(0));
test.testMinBy("hello","wonders", Comparator.comparingInt(str -> str.charAt(0)));
test.testMaxBy("hello","wonders",(str1,str2)->str1.length()-str2.length());
test.testMaxBy("hello","wonders", Comparator.comparingInt(String::length));
test.testMaxBy("hello","wonders",(str1,str2)->str1.charAt(0)-str2.charAt(0));
test.testMaxBy("hello","wonders", Comparator.comparingInt(str -> str.charAt(0)));
}
public void testBinaryOperator(Integer num1,Integer num2,BinaryOperator<Integer> result){
System.out.println(result.apply(num1,num2));
}
public void testMinBy(String str1, String str2, Comparator<String> comparator){
System.out.println(BinaryOperator.minBy(comparator).apply(str1,str2));
}
public void testMaxBy(String str1, String str2, Comparator<String> comparator){
System.out.println(BinaryOperator.maxBy(comparator).apply(str1,str2));
}
}