如何在Java的Lambda表达式中使用BinaryOperator 接口?
BinaryOperator<T>是java.util.function包中的功能接口之一,并且仅具有一个抽象方法。甲拉姆达表达或方法参考使用BinaryOperator对象作为其目标。BinaryOperator<T>接口表示一个函数,该函数采用类型T的一个参数,并返回相同类型的值。
BinaryOperator<T> 接口包含两个静态方法minBy()和maxBy()。minBy()方法返回一个BinaryOperator,返回两个元件的更大的根据指定的比较器,而maxBy()方法返回一个BinaryOperator,返回两个元件的较小的根据指定的比较器。
语法
@FunctionalInterface public interface BinaryOperator<T> extends BiFunction<T, T, T>
示例
import java.util.function.BinaryOperator;
public class BinaryOperatorTest {
public static void main(String[] args) {
BinaryOperator<Person> getMax = BinaryOperator.maxBy((Person p1, Person p2) -> p1.age-p2.age);
Person person1 = new Person("Adithya", 23);
Person person2 = new Person("Jai", 29);
Person maxPerson = getMax.apply(person1, person2);
System.out.println("Person with higher age : \n"+ maxPerson);
BinaryOperator<Person> getMin = BinaryOperator.minBy((Person p1, Person p2) -> p1.age-p2.age);
Person minPerson = getMin.apply(person1, person2);
System.out.println("Person with lower age : \n"+ minPerson);
}
}// Person classclass Person {
public String name;
public Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override public String toString(){
return "Name : "+name+", Age : "+age;
}
}输出结果
Person with higher age :Name : Jai, Age : 29Person with lower age :Name : Adithya, Age : 23
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短