java Function函数中的BinaryOperator接口用于执行lambda表达式并返回一个T类型的返回值,下面的BinaryOperator用法示例让你简单了解一下。
import java.util.function.BinaryOperator;
public class TestDemo {
public static void main(String[] args) {
BinaryOperator add = (n1, n2) -> n1 + n2;
//apply方法用于接收参数,并返回BinaryOperator中的Integer类型
System.out.println(add.apply(3, 4));
}
}
返回结果为:7
当然了,也可以用来操作字符串的lambda表达式,如下。
public class TestDemo {
public static void main(String[] args) {
BinaryOperator addStr = (n1, n2) -> n1 +"==="+ n2;
//apply方法用于接收参数,并返回BinaryOperator中的String类型
System.out.println(addStr.apply("3", "4"));
}
}
返回结果就是字符串:3==4
BinaryOperator中有两个静态方法,是用于比较两个数字或字符串的大小。
//获取更小的值
static BinaryOperator minBy(Comparator super T> comparator)
//获取更大的值
static BinaryOperator maxBy(Comparator super T> comparator)
下面用小案例来学习下这两个静态方法的使用。
minBy方法使用:
import java.util.Comparator;
import java.util.function.BinaryOperator;
public class TestDemo {
public static void main(String[] args) {
BinaryOperator bi = BinaryOperator.minBy(Comparator.naturalOrder());
System.out.println(bi.apply(2, 3));
}
}
返回结果为:2
maxBy方法使用:
public class TestDemo {
public static void main(String[] args) {
BinaryOperator bi = BinaryOperator.minBy(Comparator.naturalOrder());
System.out.println(bi.apply(2, 3));
}
}
————————————————————————————————————————————————————————持续精进-之BiFunction————————————————————————————————————————————————————————————————————
如果你正在浏览Java8的API,你会发现java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中。这些接口有一个抽象方法,会被lambda表达式的定义所覆盖。
@FunctionalInterfacepublic interface BiFunction{/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result*/R apply(T t, U u);
View Code
BiFunction 接受两个参数 返回一个结果
实战: 求两个数的 四则运算
public static Integer getSum(Integer a, Integer b, BiFunctionbiFunction) {returnbiFunction.apply(a, b);
}public static voidmain(String[] args) {
System.out.println(getSum(1,2,(a,b)->a+b));
System.out.println(getSum(1,2,(a,b)->a-b));
System.out.println(getSum(1,2,(a,b)->a*b));
System.out.println(getSum(2,2,(a,b)->a/b));
}
View Code