Functional Programming in Java venkat(15) Being Lazy part2

2023-11-04

Functional Programming in Java venkat(15): Being Lazy part2

这里是记录学习这本书 Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions 的读书笔记,如有侵权,请联系删除。

Lazy Evaluations

虽然Java在评估逻辑运算符时使用懒惰或正常顺序,但在评估方法参数时使用急切的顺序。在一个方法被调用之前,方法的所有参数都被完全评估。

it uses eager or applicative order when evaluating method arguments.

如果该方法没有使用所有传递的参数,那么程序就浪费了执行这些参数的时间和精力。

我们可以使用lambda表达式来延缓选择参数的执行。

While Java uses lazy or normal order when evaluating logical operators, it uses eager or applicative order when evaluating method arguments. All the arguments to methods are fully evaluated before a method is invoked. If the method doesn’t use all of the passed arguments, the program has wasted time and effort executing them. We can use lambda expressions to postpone the execution of select arguments.

Java编译器在调用的位置评估参数列表中的lambda表达式和方法引用。

然而,这些方法的调用会被推迟,直到它们被传递到的方法中明确调用。

我们可以利用这种行为,通过在lambda表达式中嵌入对方法的调用来延迟甚至避免方法的调用。

The Java compiler evaluates lambda expressions and method references in the argument list at the location of call. The invocation of these, however, is postponed until they are explicitly called from within the methods they’re passed to. We can take advantage of this behavior to delay or even avoid method invocation by embedding calls to them within lambda expressions.

JDK中的许多方法–包括Stream类上的方法–都会进行懒惰评估。

例如,filter()方法可能不会对目标集合中的所有元素调用作为参数传递的Predicate。

Quite a few methods in the JDK—including methods on the Stream class—do lazy evaluation. For instance, the filter() method may not invoke the Predicate, passed as an argument, on all the elements in the target collection

Starting with Eager Evaluation

  public static boolean evaluate(final int value) {
    System.out.println("evaluating ..." + value);
    simulateTimeConsumingOp(2000);
    return value > 100;
  }

  public static void simulateTimeConsumingOp(final int millseconds) {
    try { 
      Thread.sleep(2000); 
    } catch(Exception ex) { throw new RuntimeException(ex); }
  }

eagerEvaluator方法:Within the method we perform a logical and operation on the parameters.

  public static void eagerEvaluator(
    final boolean input1, final boolean input2) {
    System.out.println("eagerEvaluator called...");
    System.out.println("accept?: " + (input1 && input2));
  }

遗憾的是,由于参数在我们进入这个方法之前就已经被评估过了,所以已经来不及从这个操作自动提供的懒惰评估中获益。

Sadly, it’s too late to benefit from the lazy evaluation this operation automatically provides since the arguments are evaluated well before we enter this method.

测试一下结果

测试代码

  public static void main(final String[] args) {

    System.out.println("//" + "START:EAGER_OUTPUT");
    eagerEvaluator(evaluate(1), evaluate(2));
    System.out.println("//" + "END:EAGER_OUTPUT");
  }

输出结果

//START:EAGER_OUTPUT
evaluating ...1
evaluating ...2
eagerEvaluator called...
accept?: false
//END:EAGER_OUTPUT

如果我们运行这段代码,我们会看到在我们进入eagerEvaluator()方法之前,对evaluate()的两个调用都执行得很好。

If we run this code we’ll see both the calls to evaluate() execute well before we enter the eagerEvaluator() method.

Designing for Lazy Evaluation

如果我们知道在一个方法的执行过程中,有些参数可能不会被使用,我们可以设计它的接口以方便延迟执行一些或所有的参数。

If we know that some arguments may not be used during the execution of a method, we can design its interface to facilitate the delayed execution of some or all arguments.

  public static void lazyEvaluator(
    final Supplier<Boolean> input1, final Supplier<Boolean> input2) {
    System.out.println("lazyEvaluator called...");
    System.out.println("accept?: " + (input1.get() && input2.get()));
  }

该方法不是接收两个布尔参数,而是接收对Supplier 实例的引用。这个JDK功能接口将返回一个实例,这里是布尔值,以响应对其get()方法的调用。我们在lazyEvaluator()方法中使用的逻辑和操作将只在需要时调用get()方法。

Rather than taking two boolean parameters, the method receives references to the Supplier instances. This JDK functional interface will return an instance, Boolean in this case, in response to a call to its get() method. The logical and operation we use within the lazyEvaluator() method will invoke the get() methods only on demand.

如果我们把对evaluate()的两次调用作为参数传递给lazyEvaluator()方法,那么只有当第一次调用返回布尔值为true时,第二次调用才会被启动。

If we pass two calls to evaluate() as arguments to the lazyEvaluator() method, the second will be evaluated only if the first call returned a boolean true. Let’s run the method to see this.

调用一下

 public static void main(final String[] args) {
     
    System.out.println("//" + "START:LAZY_OUTPUT");
    lazyEvaluator(() -> evaluate(1), () -> evaluate(2));
    System.out.println("//" + "END:LAZY_OUTPUT");
  }

测试结果

//START:LAZY_OUTPUT
lazyEvaluator called...
evaluating ...1
accept?: false
//END:LAZY_OUTPUT

在我们进入lazyEvaluator()方法之前,参数没有被评估。在上面的例子中,对evaluate()的第二次调用被跳过。

The arguments are not evaluated before we enter the lazyEvaluator() method.
The second call to evaluate() was skipped in this version.

我们上面的例子中看到了懒人评估( lazy evaluation)的成本节约。当我们必须评估大量的方法,或者方法评估很耗费时间/资源时,这种技术就相当有帮助。

We saw the cost savings of the lazy evaluation. This technique is quite helpful when we have to evaluate a large number of methods or if method evaluations are time/resource consuming.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Functional Programming in Java venkat(15) Being Lazy part2 的相关文章

随机推荐

  • IEnumerable和IEnumerator 详解

    初学C 的时候 老是被IEnumerable IEnumerator ICollection等这样的接口弄的糊里糊涂 我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质 下面我们先看IEnumerable和IEnu
  • Open3D Ransac点云球面拟合(python详细过程版)

    目录 一 算法原理 二 代码实现 三 结果展示 一 算法原理 见 1 Open3D 最小二乘拟合空间球 2 Open3D RANSAC三维点云球面拟合 二 代码实现 import open3d as o3d import numpy as
  • 快速排序(四)—— 非递归排序

    前面实现了快排的递归实现 并对其进行优化 但是递归需要在栈上为函数开辟空间 32位下 栈可使用的内存大小不超过2G 如果递归较深 依然可能会发生栈溢出 这个时候递归排序就不大适用 所以需要非递归出场 1 基础思路 1 新建一个队列 队列中存
  • 汇编程序设计与计算机体系结构,《汇编程序设计与计算机体系结构:软件工程师教程》 —3.2 基本元素...

    3 2 基本元素 与高级语言不同 汇编语言是一种底层语言 它的每一行代码只执行一项操作 要想写出汇编代码 必须了解与计算机体系结构有关的一些细节 例如 CPU 寄存器 标志位 以及浮点运算功能等 对于编程新手来说 通过这些底层细节编写汇编代
  • 【Windows】DNS优选(挑选最合适的DNS服务器)

    引言 笔者在之前的文章详解DNS服务 DNS解析 DNS劫持和污染中已经详细介绍过 DNS 了 今天给大家带来一款免费的 DNS 优选工具 仅适用 Windows 帮助大家提高上网速度 拒绝 DNS 劫持 获得更佳的上网体验 下载 官网地址
  • centos7下安装Hadoop伪分布式

    虚拟机或服务器准备 安装centos7的操作系统 安装过程请自行百度 查看是否可以通网络 使用ping 163 com 如果ping不通 可以修改网卡 一般在 etc sysconfig network scripts 的文件夹下 修改if
  • 网络安全之信息收集

    第一部分 被动信息收集 如果你对网络安全入门感兴趣 那么你需要的话可以点击这里 网络安全重磅福利 入门 进阶全套282G学习资源包免费分享 1 简介 在信息收集这块区域 我将其分为两部分 第一部分即被动信息收集 第二部分即主动信息收集 对于
  • zerotier源码编译注意事项

    1 事先安装好rust 后续编译中会用到cargo 2 切换镜像源后在make Rust使用国内Crates 源 rustup源 字节跳动新的 Rust 镜像源以及安装rust rust 国内源 西京刀客的博客 CSDN博客 3 如果是比较
  • 2022杭电多校(十)

    2022杭电多校 十 文章目录 2022杭电多校 十 一 比赛小结 二 题目分析及解法 基础题 1001 Winner Prediction 1003 Wavy Tree 1004 Average Replacement 1007 Even
  • idea设置包分成显示

    分层显示之前 分层设置 取消分层显示后
  • 各种系统架构图与详细说明

    原文 各种系统架构图与详细说明 共享平台逻辑架构设计 如上图所示为本次共享资源平台逻辑架构图 上图整体展现说明包括以下几个方面 1 应用系统建设 本次项目的一项重点就是实现原有应用系统的全面升级以及新的应用系统的开发 从而建立行业的全面的应
  • 两个栈实现一个队列的功能

    1 栈 是限制的线性表插入删除必须在同一端完成 栈的特点 先进后出 入栈将数据沉入栈底 最上面的一个数据是栈顶 获取栈顶元素Top 之后要进行Pop 删除栈顶 才可以取到第二个数据 2 队列 也是对线性表的一种限定 规定插入删除数据必须在异
  • R手册(Syntax)--magrittr

    magrittr pipe lhs gt rhs forward pipe lhs为rhs第一个参数时 x gt f y 等价于 f x y lhs在任意位置时 用点 代替 z gt f x y arg 等价于 f x y arg z rh
  • codeforces 851 #432 div2 C Five Dimensional Points

    Problem codeforces com contest 851 problem C Preference Codeforces Round 432 editorial Codeforces Round 432 Div 2 C Five
  • 华为OD机试 - 单词接龙(JS)

    题目描述 单词接龙的规则是 可用于接龙的单词首字母必须要前一个单词的尾字母相同 当存在多个首字母相同的单词时 取长度最长的单词 如果长度也相等 则取字典序最小的单词 已经参与接龙的单词不能重复使用 现给定一组全部由小写字母组成单词数组 并指
  • 6.5 Java, JDBC, and MySQL Types

    MySQL Connector J 在处理 MySQL 数据类型和 Java 数据类型之间的转换方面非常灵活 通常 任何 MySQL 数据类型都可以转换为 java lang String 任何数字类型都可以转换为任何 Java 数字类型
  • VTK编译笔记

    VTK 是一个用于计算机图形学 可视化和图像处理的开源 面对对象软件系统 准备工具 编译 VTK 需要以下工具 括号内是本例中使用的版本 VTK 源码包 https vtk org download 本例下载的是 VTK 9 2 0 rc1
  • 【工具】推荐一个开源小巧的pdf分析工具

    如何定位pdf的坐标 这是最近我遇到的问题 因为我需要把几个字类似水印通过java写到pdf上 搜了几个都说要用AcrobatCD软件 这个软件也下了但是发现并没有网格坐标的功能 不知道是不是要收费 还有就是gimp软件好像也能看pdf坐标
  • vue 发送ajax请求

    一 简介 1 vue本身不支持发送AJAX请求 需要使用vue resource vue1 0版本 axios vue2 0版本 等插件实现 2 axios是一个基于Promise的HTTP请求客户端 用来发送请求 也是vue2 0官方推荐
  • Functional Programming in Java venkat(15) Being Lazy part2

    Functional Programming in Java venkat 15 Being Lazy part2 这里是记录学习这本书 Functional Programming in Java Harnessing the Power