持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
上一篇文章 我们讲了UnaryOperator
接口,这篇文章我们来讲BinaryOperator
。
BinaryOperator 接口
对比UnaryOperator
接口,我们知道,Binary 的意思是“二重的,二进制,一双”的意思。看到BinaryOperator
我们就可以知道,它是“二元操作者”。
BinaryOperator
扩展BiFunction
,因此它也需要有参数输入。BinaryOperator
接受两个相同类型的参数,并且返回的结果的类型与参数的类型相同。
我们来看BinaryOperator
接口的函数定义:
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
}
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
}
}
复制代码
BinaryOperator
接口接受两个相同类型的参数,对其进行处理之后,返回与参数相同类型的结果。
接下来我们用实际例子来介绍BinaryOperator
的用法。
使用举例
apply 方法
因为BinaryOperator
继承了BiFunction
,所以BinaryOperator
也具有BiFunction
的功能。包括其中的apply
方法和andThen
方法。
这里BinaryOperator
有别于BiFunction
的最大特点就是其输入参数和输出参数类型相同了。
public static void main(String[] args) {
BinaryOperator<Integer> binaryOperator = (n, k) -> n + k;
BinaryOperator<Integer> binaryOperator1 = Integer::sum;
}
复制代码
上面两行使用BinaryOperator
的方式得出的结果都是一样的,即输入Integer 类型的两个参数,输出两个参数相加的结果。
minBy 和maxBy 方法
在函数接口定义中我们可以发现,BinaryOperator
有两个之前没见过的方法,minBy
和maxBy
。对于这两个方法从名字也可以看出,是和大小比较有关系的。
这两个方法都是接受Compotator
参数,返回BinaryOperator
。它们分别返回两个元素之间的最大值和两个元素之间的最小值。
使用如下。
首先我们定义一个学生类:
class Student {
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
String name;
int age;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}
复制代码
然后我们使用这两个方法,观察结果:
public static void main(String[] args) {
Student s1 = new Student("xiaoming", 22);
Student s2 = new Student("xiaohong",23);
Student s3 = new Student("xiaofang",22);
Student s4 = new Student("xiaoqiang",21);
List<Student> list = Arrays.asList(s1, s2, s3, s4);
Comparator<Student> ageComparator = Comparator.comparing(Student::getAge);
BinaryOperator<Student> binaryOperator = BinaryOperator.maxBy(ageComparator);
Student olderStudent = binaryOperator.apply(s1, s2);
System.out.println("年长的学生是:" + olderStudent.getName());
BinaryOperator<Student> binaryOperator1 = BinaryOperator.minBy(ageComparator);
Student youngerStudent = binaryOperator.apply(s3, s4);
System.out.println("年轻的学生是:" + youngerStudent.getName());
}
复制代码
输出结果为:
年长的学生是:xiaohong
年轻的学生是:xiaofang
复制代码
总结
BinaryOperator
接口的使用通过上述例子我们也比较明白了,相信针对以后的工作中,不论我们遇到相关代码,还是要实现类似的功能,我们就都可以游刃有余了。