基本类型
使用为基本类型定制的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可以避免空值相关的缺陷。复制代码