Skip to content

jdk8特性

一、lambda表达式

java
Thread thread = new Thread(() -> System.out.println("aaa"));

二、jdk8新接口

函数式接口函数描述符原始类型特化
Predicate<T>T->booleanIntPredicate, LongPredicate, DoublePredicate
Consumer<T>T->voidIntConsumer, LongConsumer, DoubleConsumer
Function<T,R>T->RIntFunction<R>, IntToDoubleFunction, IntToLongFunction, LongFunction<R>, LongToDoubleFunction, LongToIntFunction, DoubleFunction<R>, ToIntFunction<T>, ToDoubleFunction<T>, ToLongFunction<T>
Supplier<T>()->TBooleanSupplier, IntSupplier, LongSupplier, DoubleSupplier
UnaryOperator<T>T->TIntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator
BinaryOperator<T>(T,T)->TIntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator
BiPredicate\<L,R\>(L,R)->boolean
BiConsumer<T,U>(T,U)->voidObjIntConsumer<T>, ObjLongConsumer<T>, ObjDoubleConsumer<T>
BiFunction<T,U,R>(T,U)->RToIntBiFunction<T,U>, ToLongBiFunction<T,U>, ToDoubleBiFunction<T,U>

2.1 使用案例

使用案例Lambda的例子对应的函数式接口
布尔表达式(List<String> list) -> list.isEmpty()Predicate<List<String>>
创建对象() -> new Apple(10)Supplier<Apple>
消费一个对象(Apple a) -> System.out.println(a.getWeight())Consumer<Apple>
从一个对象中选择/提取(String s) -> s.length()Function<String, Integer> 或 ToIntFunction<String>
合并两个值(int a, int b) -> a * bIntBinaryOperator
比较两个对象(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())Comparator<Apple> 或 BiFunction<Apple, Apple, Integer> 或 ToIntBiFunction<Apple, Apple>

三、方法引用

Lambda等效的方法引用
(Apple a) -> a.getWeight()Apple::getWeight
() -> Thread.currentThread().dumpStack()Thread.currentThread()::dumpStack
(str, i) -> str.substring(i)String::substring
(String s) -> System.out.println(s)System.out::println

四、流的中间操作

操作类型返回类型操作参数函数描述符
filter中间Stream<T>Predicate<T>T -> boolean
map中间Stream<R>Function<T, R>T -> R
limit中间Stream<T>long
skip中间Stream<T>long
sorted中间Stream<T>Comparator<T>(T, T) -> int
distinct中间Stream<T>

四、流的终端操作

操作类型目的
forEach终端消费流中的每个元素并对其应用Lambda。这一操作返回void
count终端返回流中元素的个数。这一操作返回long
collect终端把流归约成一个集合,比如List、Map 甚至是Integer。

五、中间操作和终端操作

操作类型返回类型使用的类型/函数式接口函数描述符
filter中间Stream<T>Predicate<T>T -> boolean
distinct中间Stream<T>
skip中间Stream<T>long
limit中间Stream<T>long
map中间Stream<R>Function<T, R>T -> R
flatMap中间Stream<R>Function<T, Stream<R>>T -> Stream<R>
sorted中间Stream<T>Comparator<T>(T, T) -> int
anyMatch终端booleanPredicate<T>T -> boolean
noneMatch终端booleanPredicate<T>T -> boolean
allMatch终端booleanPredicate<T>T -> boolean
findAny终端Optional<T>
findFirst终端Optional<T>
forEach终端voidConsumer<T>T -> void
collect终端RCollector<T, A, R>
reduce终端Optional