4-2 Java新特性玩转JDK8 函数式编程BiFunction
如果您还没有阅读本章须知,请先阅读➡ 本章须知
资料
- BiFunction 为函数型接口,有两个参数,有返回值。对比Function 多了一个可传入的参数。
@FunctionalInterface 接口用处是告诉其他团队成员该接口是一个函数式接口,有且只能有一个需实现的方法
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}
使用示例
两个参数的四则运算
public class Main {
public static void main(String[] args) {
System.out.println(operator(10,21,(a,b)->a+b));
System.out.println(operator(10,2,(a,b)->a-b));
System.out.println(operator(8,4,(a,b)->a*b));
System.out.println(operator(10,2,(a,b)->a/b));
}
// BiFunction<参数一类型,参数二类型,返回值类型>
public static Integer operator(Integer a, Integer b, BiFunction<Integer, Integer, Integer> bf) {
return bf.apply(a, b);
}
}
原文地址:
https://www.yuque.com/books/share/94d7e9ce-40a5-4878-97f2-c6297f679886