java8 新增了Function关键字,支持函数式编程模式,尝试学习应用到工程项目中,记录使用过程的一些经验备忘。
有过函数式编程经历的人,应该能感觉到函数式编程的简洁,直接,函数和普通变量一样,作为first class一等公民对待,应用很灵活,运用的好能够减少大量重复性的代码,提高编码效率,函数可以看成是一个代码块模板。
java8以前,function功能不支持,与之对应的是大量匿名类通过实现相关interface,代码冗长,通过实例化一个类性能上也有影响。
java8提供的function机制,实现原理是什么,性能方面有问题吗,闭包问题怎么解决,本文将逐步整理完善以解答这些疑问.
1、基本使用
Function
-
基本命名规则见文档说明
The functional interfaces in this package follow an extensible naming convention, as follows:
There are several basic function shapes, including Function (unary function from T to R), Consumer (unary function from T to void), Predicate (unary function from T to boolean), and Supplier (nilary function to R).
Function shapes have a natural arity based on how they are most commonly used. The basic shapes can be modified by an arity prefix to indicate a different arity, such as BiFunction (binary function from T and U to R).
There are additional derived function shapes which extend the basic function shapes, including UnaryOperator (extends Function) and BinaryOperator (extends BiFunction).Type parameters of functional interfaces can be specialized to primitives with additional type prefixes. To specialize the return type for a type that has both generic return type and generic arguments, we prefix ToXxx, as in ToIntFunction. Otherwise, type arguments are specialized left-to-right, as in DoubleConsumer or ObjIntConsumer. (The type prefix Obj is used to indicate that we don’t want to specialize this parameter, but want to move on to the next parameter, as in ObjIntConsumer.) These schemes can be combined, as in IntToDoubleFunction.
If there are specialization prefixes for all arguments, the arity prefix may be left out (as in ObjIntConsumer).
-
看命名规则,都是基于以下四类产生的,掌握以下几种function的使用即可。
- basic function shapes, including
- Function (unary function from T to R): 一元函数 r=f(t)
- Consumer (unary function from T to void):一元函数 f(t),无返回值
- Predicate (unary function from T to boolean): 一元函数boolean r=f(t)
- Supplier (nilary function to R)
- BiFunction (binary function from T and U to R). 二元函数r=f(t,u)…
- basic function shapes, including
2、优缺点
优点
模板代码,提升编码效率,简洁,高阶Function,灵活性和可读性之间要把握一个度,取得平衡。
缺点
可读性差
3、注意事项
闭包问题,变量作用域问题