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

  • 相关阅读:
    大白话解说,半分钟就懂 --- 分布式与集群是什么 ? 区别是什么?
    intellij idea中去除@Autowired注入对象的红色波浪线提示
    用JQuery获取事件源怎么写
    springBoot 配置url 访问图片
    地图服务 纬度、经度对应坐标轴x,y
    5个问题带你了解export和import的使用以及export和export defalut 的区别
    5个你可能不知道的html5语义化标签
    CSS选择器[attribute | = value] 和 [attribute ^ = value]的区别
    前端ps实用小技巧
    7步教你使用git命令上传本地代码至github仓库(小白向)
  • 原文地址:https://www.cnblogs.com/coding-now/p/14660561.html
Copyright © 2011-2022 走看看