zoukankan      html  css  js  c++  java
  • java8提供的Function,你了解多少,一起来看看

    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)…

    2、优缺点

    优点

    模板代码,提升编码效率,简洁,高阶Function,灵活性和可读性之间要把握一个度,取得平衡。

    缺点

    可读性差
    

    3、注意事项

    闭包问题,变量作用域问题

    4、结合Stream

    5、关于函数式编程

  • 相关阅读:
    多线程-threading模块3
    多线程-threading模块2
    多线程-threading模块
    mac下载模块时报错OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/chardet'
    python+selenium高亮显示正在操作的页面元素
    判断元素是否存在页面的两种不同写法
    [转]Python+Selenium之expected_conditions:各种判断(上)
    MACE移植要求
    采用Tensorflow内部函数直接对模型进行冻结
    如何正确可视化RAW(ARW,DNG,raw等格式)图像?
  • 原文地址:https://www.cnblogs.com/coding-now/p/14660561.html
Copyright © 2011-2022 走看看