java反射api研究_深入研究Java 8中的可选类API

java反射api研究

作为Java程序员,我们所有人都经历了以下情况:我们调用一个方法来获取某个值,然后代替直接对返回值调用某些方法,我们首先必须检查返回值是否不为null,然后在返回值。 这是像Guava这样的外部API试图解决的难题 。 此外,其他JVM语言(例如Scala,Ceylon和其他语言)也将这些功能引入了核心API。 在我以前的文章中,我写了关于一种这样的JVM语言(即Scala)的支持的文章 。

Java的较新版本(即Java 8)引入了一个名为Optional的新类。 可选类的Javadoc说:

可以包含或不包含非null值的容器对象。 如果存在值,则isPresent()将返回true,而get()将返回该值。

在这篇文章中,让我们看一下Optional类中存在的每个方法,并用一个或两个示例进行解释。

of

返回带有指定的当前非空值的Optional。

此方法是用于创建Optional类的实例的工厂方法。 这里要注意的一点是,传递给创建实例的值必须为非null。 如果传递的值为null,则抛出NullPointerException

//Creating an instance of Optional using the factory method.
Optional<String> name = Optional.of("Sanaulla");
//This fails with a NullPointerException.
Optional<String> someNull = Optional.of(null);

ofNullable

返回描述指定值的Optional,如果非空,则返回空值。

of方法类似,唯一的区别是此方法还处理空值。 一个例子:

//This represents an instance of Optional containing no value
//i.e the value is 'null'
Optional empty = Optional.ofNullable(null);

isPresent

很简单的理解:

如果存在值,则返回true,否则返回false。

就像是:

//isPresent method is used to check if there is any 
//value embedded within the Optional instance.
if (name.isPresent()) {//Invoking get method returns the value present//within the Optaional instance.System.out.println(name.get());//prints Sanaulla
}

get

如果此Optional中存在一个值,则返回该值,否则抛出NoSuchElementException。

此方法用于检索Optional实例中存在的值。 我们在上面看到了一个这样的例子。 让我们看一个抛出NoSuchElementException的例子:

//The below code prints: No value present 
try {//Invoking get method on an empty Optaional instance //throws NoSuchElementException.System.out.println(empty.get());
} catch (NoSuchElementException ex) {System.out.println(ex.getMessage());
}

ifPresent

如果存在值,请使用该值调用指定的使用者,否则不执行任何操作。

要了解此方法,您必须了解Consumer类 。 简而言之,Consumer是一个具有单个抽象方法的类,用于消费一些值并对其执行一些操作而不返回任何值。 在Java 8中,可以将lambda表达式传递给期望使用Consumer接口的方法。
如果Optional实例中存在该值,则上述方法接受代码/ lambda表达式块以执行某些操作。 就像是:

//ifPresent method takes a lambda expression as a parameter.
//The lambda expression can then consume the value if it is present
//and perform some operation with it.
name.ifPresent((value) -> {System.out.println("The length of the value is: " + value.length());
});

orElse

返回值(如果存在),否则返回其他。

此方法要么返回Optional实例中存在的值,否则返回返回作为参数传递给orElse方法的值。 让我们看一个例子:

//orElse method either returns the value present in the Optional instance
//or returns the message passed to the method in case the value is null.
//prints: There is no value present!
System.out.println(empty.orElse("There is no value present!"));
//prints: Sanaulla
System.out.println(name.orElse("There is some value!"));

orElseGet

该方法类似于上述方法。 区别在于如何获取默认值。 在orElse方法中,我们传递了固定的字符串作为默认值,但在orElseGet方法中,我们传递了Supplier接口的实现,该接口具有一种用于生成默认值的方法。 让我们看一个例子:

//orElseGet is similar to orElse with a difference that instead of passing 
//a default value, we pass in a lambda expression which generates the default 
//value for us.
//prints: Default Value
System.out.println(empty.orElseGet(() -> "Default Value"));
//prints: Sanaulla
System.out.println(name.orElseGet(() -> "Default Value"));

orElseThrow

返回包含的值(如果存在),否则抛出异常,由提供的供应商创建。

就像在方法orElseGet我们通过一个供应商的接口 ,但在orElseThrow方法我们通过lambda表达式/方法引用抛出一个异常时,未找到该值。 一个例子:

try {//orElseThrow similar to orElse method, instead of returning a default//value, this method throws an exception which is generated from //the lambda expression/method reference passed as a param to the method.empty.orElseThrow(ValueAbsentException::new);
} catch (Throwable ex) {//prints: No value present in the Optional instanceSystem.out.println(ex.getMessage());
}

而且ValueAbsentException的定义是:

class ValueAbsentException extends Throwable {public ValueAbsentException() {super();}public ValueAbsentException(String msg) {super(msg);}@Overridepublic String getMessage() {return "No value present in the Optional instance";}
}

map

从有关地图方法的文档中:

如果存在值,则将提供的映射函数应用于该值,如果结果为非null,则返回描述结果的Optional。 否则,返回一个空的Optional。

此方法用于对Optional实例中存在的值应用一组操作。 这组操作以lambda表达式的形式传递,该表达式表示Function接口的实现。 如果您不熟悉Function接口,那么请花一些时间在这里阅读我以前关于同一主题的博客文章。 让我们看一下map方法的示例:

//map method modifies the value present within the Optional instance
//by applying the lambda expression passed as a parameter. 
//The return value of the lambda expression is then wrapped into another
//Optional instance.
Optional<String> upperName = name.map((value) -> value.toUpperCase());
System.out.println(upperName.orElse("No value found"));

flatMap

flatMap方法的文档中:

如果存在一个值,则对它应用提供的带有可选参数的映射函数,返回该结果,否则返回一个空的Optional。 此方法与map(Function)相似,但是提供的映射器是其结果已经是Optional的映射器,如果调用它,则flatMap不会使用附加的Optional对其进行包装。

此方法与map方法非常相似,不同之处在于传递给它的映射函数的返回类型。 在使用map方法的情况下,映射函数的返回值可以是任何类型T ,而在使用flatMap方法的情况下,映射函数的返回值只能是Optional类型的

让我们看一下上面的示例,其中将map方法重写为flatMap方法:

//flatMap is exactly similar to map function, the differece being in the
//return type of the lambda expression passed to the method.
//In the map method, the return type of the lambda expression can be anything
//but the value is wrapped within an instance of Optional class before it 
//is returned from the map method, but in the flatMap method the return 
//type of lambda expression's is always an instance of Optional.
upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println(upperName.orElse("No value found"));//prints SANAULLA

filter

通过将要应用于值的条件传递给filter方法,该方法用于将值限制在Optional实例内。 该文档说:

如果存在一个值,并且该值与给定谓词匹配,则返回描述该值的Optional,否则返回一个空的Optional。

到现在为止,您必须已经知道如何将一些代码块传递给该方法。 是的,它是lambda表达式。 对于这种方法,我们必须传递一个lambda表达式,该表达式将是Predicate接口的实现。 如果您不熟悉谓词界面,请花一些时间阅读这篇文章。

现在,让我们看一下filter方法的不同用法,即满足条件和不满足条件的两个示例。

//filter method is used to check if the given optional value satifies
//some condtion. If it satifies the condition then the same Optional instance
//is returned, otherwise an empty Optional instance is returned.
Optional<String> longName = name.filter((value) -> value.length() > 6);
System.out.println(longName.orElse("The name is less than 6 characters"));//prints Sanaulla//Another example where the value fails the condition passed to the 
//filter method.
Optional<String> anotherName = Optional.of("Sana");
Optional<String> shortName = anotherName.filter((value) -> value.length() > 6);
//prints: The name is less than 6 characters
System.out.println(shortName.orElse("The name is less than 6 characters"));

这样,我就向您介绍了Optional类中存在的各种方法。 让我将以上所有示例汇总为一个示例,如下所示:

public class OptionalDemo {public static void main(String[] args) {//Creating an instance of Optional//This value can also be returned from some method. Optional<String> name = Optional.of("Sanaulla");//This represents an instance of Optional containing no value//i.e the value is 'null'Optional empty = Optional.ofNullable(null);//isPresent method is used to check if there is any //value embedded within the Optional instance.if (name.isPresent()) {//Invoking get method returns the value present//within the Optaional instance.System.out.println(name.get());}try {//Invoking get method on an empty Optaional instance //throws NoSuchElementException.System.out.println(empty.get());} catch (NoSuchElementException ex) {System.out.println(ex.getMessage());}//ifPresent method takes a lambda expression as a parameter.//The lambda expression can then consume the value if it is present//and perform some operation with it.name.ifPresent((value) -> {System.out.println("The length of the value is: " + value.length());});//orElse method either returns the value present in the Optional instance//or returns the message passed to the method in case the value is null.System.out.println(empty.orElse("There is no value present!"));System.out.println(name.orElse("There is some value!"));//orElseGet is similar to orElse with a difference that instead of passing //a default value, we pass in a lambda expression which generates the default //value for us.System.out.println(empty.orElseGet(() -> "Default Value"));System.out.println(name.orElseGet(() -> "Default Value"));try {//orElseThrow similar to orElse method, instead of returning a default//value, this method throws an exception which is genereated from //the lambda expression/method reference passed as a param to the method.empty.orElseThrow(ValueAbsentException::new);} catch (Throwable ex) {System.out.println(ex.getMessage());}//map method modifies the value present within the Optional instance//by applying the lambda expression passed as a parameter. //The return value of the lambda expression is then wrapped into another//Optional instance.Optional<String> upperName = name.map((value) -> value.toUpperCase());System.out.println(upperName.orElse("No value found"));//flatMap is exactly similar to map function, the differece being in the//return type of the lambda expression passed to the method.//In the map method, the return type of the lambda expression can be anything//but the value is wrapped within an instance of Optional class before it //is returned from the map method, but in the flatMap method the return //type of lambda expression's is always an instance of Optional.upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));System.out.println(upperName.orElse("No value found"));//filter method is used to check if the given optional value satifies//some condtion. If it satifies the condition then the same Optional instance//is returned, otherwise an empty Optional instance is returned.Optional<String> longName = name.filter((value) -> value.length() > 6);System.out.println(longName.orElse("The name is less than 6 characters"));//Another example where the value fails the condition passed to the //filter method.Optional<String> anotherName = Optional.of("Sana");Optional<String> shortName = anotherName.filter((value) -> value.length() > 6);System.out.println(shortName.orElse("The name is less than 6 characters"));}}

以及上面代码的输出:

Sanaulla
No value present
The length of the value is: 8
There is no value present!
Sanaulla
Default Value
Sanaulla
No value present in the Optional instance
SANAULLA
SANAULLA
Sanaulla
The name is less than 6 characters

参考:在Experiences Unlimited博客上,我们的JCG合作伙伴 Mohamed Sanaulla深入研究了Java 8中的Optional类API 。

翻译自: https://www.javacodegeeks.com/2013/09/deep-dive-into-optional-class-api-in-java-8.html

java反射api研究

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/346932.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【卷积码系列1】(n,k,m)卷积码的编码原理详解及MATLAB实现

关注公号【逆向通信猿】更精彩!!! 原理 编码电路图 ( n , k , m ) (n,k,m) (n,k,

用于SaaS和NoSQL的Jdbi

一个自然的接口&#xff0c;用于与CRM&#xff0c;ERP&#xff0c;会计&#xff0c;营销自动化&#xff0c;NoSQL&#xff0c;平面文件等基于Java的数据集成 Jdbi是Java的SQL便利库&#xff0c;它为JDBC提供更自然的Java数据库接口&#xff0c;该接口易于绑定到域数据类型。 该…

【卷积码系列2】(n,k,m)卷积码的生成多项式矩阵系数转网格图描述(不使用MATLAB库函数)

关注公号【逆向通信猿】更精彩!!! 回顾 之前关于(3,1,3)卷积码的维特比译码仿真写过一篇文章(基于C语言实现): 卷积码Viterbi译码算法基本原理及C语言实现 文中从概率的角度出发,对卷积码的基于硬判决和软判决维特比译码原理进行了阐述,最后以(3,1,3)系统卷积码为例…

【卷积码系列3】(n,k,m)卷积码的维特比译码实现(不使用MATLAB库函数)及性能对比(vitdec函数不使用MATLAB库函数【全部代码需私信另外付费获取】)

理论基础 MATLAB库函数polly2trellis(卷积码生成多项式转网格图描述)的实现过程详解 上面这篇仅作为了解!!! 【卷积码系列1】(n,k,m)卷积码的编码原理详解及MATLAB实现 【卷积码系列2】(n,k,m)卷积码的生成多项式矩阵系数转网格图描述(不使用MATLAB库函数) 维特比译码曲…

【数字信号处理】基于DFT的滤波系列1

一、引言 离散傅立叶变换(DFT)是很多数字信号处理(DSP)层面的核心,因此我们从这块开始。 我们首先快速回顾一下 DFT 的一些要点。 该模块这一部分的完整内容列表是: DFT 回顾 – 实数和复数形式一维(例如时间序列)数据的 DFT 滤波DFT 滤波的非理想行为窗口化二维图像的D…

udt java_Java DB中的Java用户定义类型(UDT)

udt javaJava DB是基于Java编程语言和SQL的关系数据库管理系统。 这是Apache软件基金会的开源Derby项目的Oracle版本。 Java SE 7 SDK中包含Java DB。 用户定义类型&#xff08;UDT&#xff09;是Java类&#xff0c;其实例&#xff08;对象&#xff09;存储在数据库表列中。 U…

【自适应盲均衡9】基于判决反馈的多径衰落信道的盲均衡与MATLAB仿真(CMA-DFE)

关注公号【逆向通信猿】更精彩!!! 关于基于常模准则的盲均衡(即CMA)的基础知识,首先可参考本人博客 【自适应盲均衡2】多径衰落信道的复数常模算法(CMA)的理论推导与MATLAB仿真 引言——判决反馈均衡器(DFE)的引入 线性FIR均衡器一直作为克服信道失真的主要手段。它对…

Java批处理教程

在当今世界&#xff0c;互联网已经改变了我们的生活方式&#xff0c;其主要原因之一是大多数日常琐事都使用互联网。 这导致可用于处理的大量数据。 其中涉及大量数据的一些示例是处理工资单&#xff0c;银行对帐单&#xff0c;利息计算等。因此&#xff0c;请设想一下&#x…

【自适应盲均衡10】基于判决引导(Decision Directed)的多径衰落信道双模式盲均衡算法与MATLAB仿真(DD-CMA)

关注公号【逆向通信猿】更精彩!!! 引言 判决反馈均衡器(Decision Feedback Equalizer, DFE)虽然能够避免线性FIR均衡器的噪声增强,适用于具有深度谱零点的信道均衡;但是容易产生误收敛情况,针对该问题有人提出了预测判决反馈均衡器(PDFE),这个后续再说。 此次要讨论…

【数字信号处理】基于DFT的滤波系列2(含MATLAB代码)

关注公号【逆向通信猿】更精彩!!! 三、时频域的“数” 在该节的大部分内容中,我们将使用无量纲数字序列的数据。然而,对于现实世界的数据,这些数字将具有基础单位。在本节中,将解释时域和频域之间的联系。 假设有N个采样频率为 f s f_s f

编写junit 测试_使用JUnit和Repeat注​​释编写有效的负载测试

编写junit 测试EasyTest最近推出了一组新的注释&#xff0c;可帮助其用户编写有效的测试用例。 进入EasyTest的两个主要注释是&#xff1a; 重复 持续时间 今天&#xff0c;我们将讨论重复标注。 一种新的方法级别注释 重复已添加到EasyTest Framework。 此批注可用于重复…

【数字信号处理】基于DFT的滤波系列3之插值滤波(含MATLAB代码)

四、基于DFT的(理想)滤波 例2:一个“警告” “理想DFT滤波器”虽然简单、有效,但可能会导致意想不到的问题。在博客 【数字信号处理】基于DFT的滤波系列2(含MATLAB代码) 中,数据本身是理想的,由完美的谐波组成,这些谐波在频域中以单一频率理想地表示(无频谱泄漏),这…

Java 9中的无限集

一套 甲Set是元素的集合&#xff0c;从而在任何给定的元件Set只出现一次。 更正式地说&#xff0c;集合不包含元素e1和e2对&#xff0c;因此e1.equals(e2) 。 我们可以像这样在Java 9中轻松创建Set &#xff1a; final Set<Integer> s Set.of(1, 2, 3); System.out.p…

json文件读取之reader.onload中的定义的变量在其函数外部进行处理

采用FileReader读取json文件时,发现只能在reader.onload函数内部获取文件数据,且无法在函数外部访问其内部定义的变量,在网上查阅资料,发现也有博客提到这个问题,如下: VUE的reader.onload方法怎么把值抛出去 在reader.onload中的定义的变量如何在外部调用 … 网上其他…

【数字信号处理】基于DFT的滤波系列4之加窗(含MATLAB代码)

四、基于DFT的(理想)滤波 加窗以减少频谱泄漏 在上面的例子中,整数次谐波被用来产生理想中的示例。这意味着一个完整的整数周期适合正在使用的样本数。一个明显的问题是,如果使用非整数周期数(以及谐波)会怎样?答案是远没有那么有效。 在现实世界中,从这个意义上说,数…

结构为键值的map_在Java中增加Map值的最有效方法-只需搜索键一次

结构为键值的map这个问题可能被认为太基础了&#xff0c;但是在论坛中经常被问到。 在本文中&#xff0c;我将讨论一种仅在Map ONCE中搜索键的方法。 让我们首先来看一个例子。 假设我正在使用Map创建一个字符串频率列表&#xff0c;其中每个键是一个正在计数的String &#x…

【数字信号处理】基于DFT的滤波系列5之二维DFT滤波(含MATLAB代码)

五、二维DFT滤波 前几节介绍的用于对时间序列滤波的原理也可用于对图像的滤波,采用二维傅里叶变换技术。 下图为一幅图像的二维DFT(2D DFT)变换后的幅度值,该图像仅由一个恒定强度组成,因此它是0Hz分量——背景强度。在可视化 2D DFT 的结果时通常使用fftshift(),因此 DC…

Vaadin教程

1.简介 当您是后端开发人员时&#xff0c;您会听到人们说您无法创建内置HTML的UI页面并且无法使用CSS设置样式时所引起的痛苦。 就像成为后端开发人员一样&#xff0c;它具有已知的局限性&#xff0c;即我们可以播放和运行大型生产后端应用程序&#xff0c;但不能创建漂亮的页面…

【定时同步系列5】Farrow内插器结构原理和MATLAB实现

引言 通常我们接收到的信号是过采样的 x ( m T s ) x(mT_s) x(mT

【数字信号处理】基于DFT的滤波系列6之维纳滤波理论推导与MATLAB仿真

维纳(Wiener)滤波 引言 罗伯特维纳(Norbert Wiener)是一位对信号处理理论做出重大贡献的神童。维纳滤波是其中之一,维纳-辛钦(Wiener-Khinchin)定理是另一个表明信号的功率谱密度是其自相关函数的傅里叶变换的定理。他也是控制论的“鼻祖”。 我们将看一下维纳滤波器的一个…