《Java8函数式编程》读书笔记---类库
发布日期:2021-08-26 15:47:35 浏览次数:2 分类:技术文章

本文共 1584 字,大约阅读时间需要 5 分钟。

基本类型

使用为基本类型定制的IntStream可以提升系统性能。 在java中,int占4个字节,Integer占16个字节。在一些情况下使用基本类型更加高效,所以java8有一些专门的基本类型操作,例如: mapToInt(),返回IntStream对象。

重载

方法出现重载overload,javac会挑出最具体的那个,否则报错。

@FunctionalInterface

函数接口上面需要添加次注释。复制代码

接口中的默认方法,(接口可以有方法的实现)

以下代码片段为Iterable接口中的foreach方法:

/**     * Performs the given action for each element of the {
@code Iterable} * until all elements have been processed or the action throws an * exception. Unless otherwise specified by the implementing class, * actions are performed in the order of iteration (if an iteration order * is specified). Exceptions thrown by the action are relayed to the * caller. * * @implSpec *

The default implementation behaves as if: *

{
@code * for (T t : this) * action.accept(t); * }
* * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null * @since 1.8 */ default void forEach(Consumer
action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }复制代码

在Iterable接口中有一个方法,该方法是default修饰的,成为默认方法。这种方法存在的原因是为了解决不同java版本的兼容问题。 java1-7的代码,可以直接在jvm8里面运行,这是java最大的优势,但是java8加入了一些新的特性,导致兼容存在问题,比如: java8中为Collection接口增加了stream方法,导致所有自建的集合类必须实现stream方法。但是在java7中的自建集合类,并没有实现该方法。这样旧代码在java8中无法编译通过。

这种兼容性问题的解决方案就是默认方法。上面的例子中,把stream方法变为默认方法,如果子类没有实现此方法,就直接使用接口的默认方法。这样java7的自建集合就可以在java8中编译通过。

接口的静态方法

java8还允许接口有静态方法,如常用的Stream.of()复制代码

Optional对象

当你不确定返回的对象是否为空时,可以使用Optional对象作为返回值。他表示:null或者对象。Optional可以避免空值相关的缺陷。复制代码

转载地址:https://blog.csdn.net/weixin_33890499/article/details/91367479 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:前端实习生,快到碗里来~
下一篇:前端笔试题收集(笔记)

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月24日 12时58分34秒