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、关于函数式编程

  • 相关阅读:
    php性能测试工具
    linux的openssl
    Nginx与Apache的Rewrite规则的区别
    mysql索引总结----mysql 索引类型以及创建
    不支持正在使用的 .Net 组帧模式。有关详细信息,请参阅服务器日志--解决方案
    c#获取网页源代码
    关于线程间操作无效: 从不是创建控件“xx”的线程访问它,错误解决方法(自定义委托和系统委托Action或Func解决)
    联想笔记本官网驱动下载
    easy ui combotree的操作
    c# 搜狗拼音输入法,刷输入速度和累计输入
  • 原文地址:https://www.cnblogs.com/coding-now/p/14660561.html
Copyright © 2011-2022 走看看