摘抄程序人生

Java 8函数式编程设计(Functional interfa

2017-06-11  本文已影响113人  简放视野

Java 8函数式编程设计(Functional interfaces)

通过阅读JDK 8的java.util.function包源码,意在理解Java的函数式接口设计。

读后自己的理解:Java函数式编程的核心是将最基础的数学函数抽象成接口对象,可在已有的接口上进行积木拼插。最基础的数学函数包括一元函数、谓词、二元函数、运算符计算,对应的Java接口分别是Function、Predicate、BiFunction、BinaryOperator。

源码阅读笔记:jdk-8-Functional-Interface


API


@FunctionalInterface


Functional interfaces

一元函数

Function<T, R>
Consumer<T>
Predicate<T>
Supplier<T>

使用图表方式总结如下:

一元函数 方法 类型转换 组合方法 基本类型专用类
Function<T, R> R apply(T t) T->R compose(before)、andThen(after) IntFunction<R>、ToIntFunction<T>、IntToLongFunction
Consumer<T> void accept(T t) T->void andThen(after) IntConsumer
Predicate<T> boolean test(T t) T->boolean and、negate、or IntPredicate
Supplier<T> T get() *->T IntSupplier、BooleanSupplier

二元函数

BiFunction<T, U, R>
BiConsumer<T, U>
BiPredicate<T, U>

使用图表方式总结如下:

二元函数 方法 类型转换 组合方法 基本类型专用类
BiFunction<T, U, R> R apply(T t, U u) (T、U)->R andThen(Function after) ToIntBiFunction<T, U>
BiConsumer<T, U> void accept(T t, U u) (T、U)->void andThen(after) ObjIntConsumer<T>
BiPredicate<T, U> boolean test(T t, U u) (T、U)->boolean and、negate、or

扩展的运算符

UnaryOperator<T>
BinaryOperator<T>
运算符 父类 组合方法 基本类型专用类
UnaryOperator<T> Function<T, T> IntUnaryOperator: int applyAsInt(int operand)
BinaryOperator<T> BiFunction<T, T, T> minBy、maxBy IntBinaryOperator: int applyAsInt(int left, int right)

Use Cases

Optional<T>
上一篇下一篇

猜你喜欢

热点阅读