JDK 8 new features
Lambda Expressions
- A lambda expression is an anonymous function. A function that doesn’t have a name and doesn’t belong to any class;
- Syntax:
(parameter_list) -> {function_body}
如果只有1个参数,可以省去括号, 如果函数体只有一句,可以省略大括号; - 一个方法method(函数function)包含4部分: 方法名, 参数列表, 方法体, 返回值类型. 一个 lambda 表达式: 1)没有名字; 2) 有参数列表; 3) 有函数体; 4) 没有返回值类型, 但是函数可以返回值, JVM 动态侦测类型;
- Java 8 之前, 很多地方我们使用匿名内部类, 8及之后, 都可以使用 lambda 表达式来替换;
- 通常使用 lambda 表达式的地方 -> 函数式接口(只有一个抽象的方法), 比如 Callable, Runnable, 各种 Listener;
Method References 方法引用
它通常是 lambda 表达式的一种缩写形式str -> System.out.println(str)
->System.out::println
4种类型的方法引用:- Method reference to an instance method of an object – object::instanceMethod
- Method reference to a static method of a class – Class::staticMethod
- Method reference to an instance method of an arbitrary object of a particular type – Class::instanceMethod
- Method reference to a constructor – Class::new
Functional Interfaces 函数式接口
- An interface with only single abstract method is called functional interface(Single Abstract Method interfaces);
- JDK 预先定义的函数式接口 链接;
- 可选的 Annotation: @FunctionalInterface 编译时能侦测是不是符合函数式接口定义;
- 定义的时候, 除了这个唯一的抽象的方法, 可以有任何多个非抽象的实例方法或静态方法;
- Java 8 之前通常使用匿名内部类来实现这种接口, Java 8 及以后可以使用 lambda 表达式;
接口增加 default method and static method
- Java 8 之前接口只能有抽象方法, 所有的方法默认都是 public & abstract;
- Java 8 使接口可以有 default 方法和 static 方法;
- default method and static method 可以是已存在的接口添加新的功能而不影响原有逻辑;
- static method 类似 default method, 只是实现者不能 override 这些方法;
default method 值方法签名前加
default
关键字;default void myDefaultMethod(){ ... }
- 抽象类可以有构造函数, interface 不行. 接口侧重定义规范, 抽象类侧重实现整体, 细节留空;
- 一个类实现多个接口中如果有相同的 default 方法, 编译会报错, 需要在实现类中解决冲突;
Stream API (java.util.stream)
- using streams we can perform various aggregate operations on the data returned from collections, arrays, Input/Output operations;
Stream 可顺序也可以通过并行执行(Parallel execution)的方式(理论上,实际不一定)加快执行速度;
- stream.sequential()
- stream.parallel()
- 步骤: 1) 一次创建 Stream; 2) 0或多个中间操作; 3) 一次终止操作;
- 例子:
Arrays.asList("line0", "line1").stream().filter(str->str.length()<6).count()
常见的操作:
Intermediate operations:- filter - Exclude all elements that don't match a Predicate.
- map - Perform a one-to-one transformation of elements using a Function.
- flatMap - Transform each element into zero or more elements by way of another Stream.
- peek - Perform some action on each element as it is encountered. Primarily useful for debugging.
- distinct - Exclude all duplicate elements according to their .equals behavior. This is a stateful operation.
- sorted - Ensure that stream elements in subsequent operations are encountered according to the order imposed by a Comparator. This is a stateful operation.
- limit - Ensure that subsequent operations only see up to a maximum number of elements. This is a stateful, short-circuiting operation.
- skip - Ensure that subsequent operations do not see the first n elements. This is a stateful operation.
Terminal operations:
- forEach - Perform some action for each element in the stream.
- toArray - Dump the elements in the stream to an array.
- reduce - Combine the stream elements into one using a BinaryOperator.
- collect - Dump the elements in the stream into some container, such as a Collection or Map.
- min - Find the minimum element of the stream according to a Comparator.
- max - Find the maximum element of the stream according to a Comparator.
- count - Find the number of elements in the stream.
- anyMatch - Find out whether at least one of the elements in the stream matches a Predicate. This is a short-circuiting operation.
- allMatch - Find out whether every element in the stream matches a Predicate. This is a short-circuiting operation.
- noneMatch - Find out whether zero elements in the stream match a Predicate. This is a short-circuiting operation.
- findFirst - Find the first element in the stream. This is a short-circuiting operation.
- findAny - Find any element in the stream, which may be cheaper than findFirst for some streams. This is a short-circuiting operation.
- stream 可以 infinite;
- stream 处理可以短路(Short-circuiting), 不在执行剩下的, 对于无限 stream 最有用;
Optional
- 改变编程习惯, 避免 NullPointerException - 原来直接用, 现在用各种方法;
- A container object which may or may not contain a non-null value;
- 创建: 1)
Optional.empty()
, 2)Optional.of(T value)
, 3)Optional.ofNullable(T value)
; - 判断:
isPresent()
; - 获得:
get()
, 若null -> NoSuchElementException; 获得带 fallback 机制:
- 若空返回 other:
orElse(T other)
- 若空执行函数接口返回值:
orElseGet(Supplier<? extends T> other)
- 若空抛出特定异常:
orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
- 若空返回 other:
其它
- 非空并且满足predicate
filter(Predicate<? super T> predicate)
; map(Function<? super T, ? extends U> mapper)
flatMap(Function<? super T, Optional<U>> mapper)
- 非空并且满足predicate
- StringJoiner 类似 guava 的 Joiner, 前缀, 后缀, 分隔符.
- Arrays.parallelSort -> 多线程排序加速
java.util.function 一些常见的函数
- Function<T, R> - take a T as input, return an R as ouput
- Predicate
- take a T as input, return a boolean as output - Consumer
- take a T as input, perform some action and don't return anything - Supplier
- with nothing as input, return a T - BinaryOperator
- take two T's as input, return one T as output, useful for "reduce" operations
- java.time 包
refer: