l@[TOC]
函数式接口概述
jdk1.8 引入了一个核心概念:函数式接口(Functional Interface)。如果一个接口有且只有一个未实现的方法,那这个接口就称为函数式接口。并且引入了一个新的注解:@FunctionalInterface , 把这个注解放到接口定义之前,就表明这个接口是一个函数式接口,编译器会检查该接口是否只有一个未实现的方法,如果定义了多个或者没有定义,编译则会报错。
不过这个注解不是必须的,就算没有加这个注解,虚拟机也能识别出函数式接口。这个注解按我的理解,主要是为了防止误操作,加了这个注解之后接口就不会允许出现多个未实现方法了。
Lambda 表达式
函数式接口最大的一个特点是:可以用Lambda实例化它们。Lambda表达式能够让你将函数作为一个方法参数进行传递。Lambda在代码简洁性和可读性方面带来了极大的提升,在1.8之前像匿名内部类,事件监听器的写法都非常冗长,可读性差。Lambda使代码更加紧凑。
Lambda的组成
Lambda表达式由3部分组成:
一是被括号包裹的以逗号分隔的参数列表,参数即接口的唯一方法的参数;
例如: () 或者 (param1, param2)
二是一个箭头符号: ->
三是方法体,方法体可以是表达式和代码块。语法如下:
方法体为表达式:该表达式的值作为方法的返回值
(param) -> expression
方法体为代码块,需要用{}包裹起来,并且需要加一个return 作为方法返回值,如果方法不需要返回值,则不需要return
(param) -> {statements;}
在jdk之前, 事件监听器的实现一般是这样:
button.addListener(
new ActionListener(){
@Override
public void perform(ActionEvent){
Systen.out.println("old ways");
}
}
)
Lambda表达式简化写法:
button.addListener((event)->Systen.out.println(“lambda ways”));
函数式接口和lambda表达式是函数式编程的基础。每个Lambda都对应一个函数式接口。我们可以直接使用Lambda而不用为每个Lambda表达式自定义一个函数式接口,是因为jdk8为我们提供了许多常用的函数式接口:Function , Consumer, Supplier, Predicate。
函数式接口:Function
Function代表我们日常用的最多的函数:接受一个参数、返回一个结果。
直接上源码:
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}
R apply(T t) 就是这个接口的唯一未实现方法,Lambda表达式也就是实现了这个方法。另外有2个方法比较难理解: compose(Function before) 和 andThen(Function after)
这两个方法是为了函数式接口的复合使用,类似与 f(g(x))。 这意味着可以把多个简单的Lambda复合成复杂的表达式
使用示例:
public static void main(String[] args) {
Function<Integer,Integer> f = (i)-> {return i+1;};
Function<Integer,Integer> g = (x) -> {return x*2;};
Function<Integer,Integer> m = (x) -> {return x-10;};
Integer compose = f.compose(g).apply(3);
Integer then = f.andThen(g).apply(3);
System.out.println(compose);
System.out.println(then);
}
输出结果是: 7,8
compose方法是先执行before函数,将before函数的结果作为输入再执行。
andThen方法是先执行本函数,将本函数的结果作为after函数的输入再执行
f.compsoe(g) 相当于 f(g(x)), f.andThen(g) 相当于 g(f(x)); 有了这两个方法之后,Function就可以像数学函数一样组合、嵌套使用。
上例中 f.compsoe(g).compose(m).apply(2) 相当于 ((2-10)2)+1= -15。 f.compose(g).andThen(2) 相当于 ((22)+1)-10=-5。
函数式接口: Consumer
Consumer消费者,顾名思义即针对某个东西我们来消费、使用它。因此它包含一个有输入无输出的accept方法。
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
我们可以注意到:Consumer没有compose方法,compose方法需要before函数的结果作为输入,而accet方法没有返回值,也就无法进行compose复合了。
使用示例:
Collection接口继承了另一个迭代器接口Interable, Interable接口中包含一个用于遍历集合的forEach方法,它的参数就是 Consumer接口。
/**
*
* @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<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
函数式接口: Supplier
顾名思义:提供者就是提供一个对象供使用,因此Supplier接口包含一个有输出无输入的get方法。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
使用示例
jdk提供的对象操作工具类Objects中,有一个requireNonNull方法, 它的作用是判断某对象是否为null, 为null则抛出空指针异常并指定异常信息。异常信息就是通过一个Supplier接口生成的
Objects类
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
if (obj == null)
throw new NullPointerException(messageSupplier.get());
return obj;
}
使用举例:
String param = null;
Objects.requireNonNull(param, ()->{return "参数不允许为null";});
函数式接口: Predicate
断言型接口:它的作用是进行逻辑判断,因此 Predicate提供了接受一个参数并返回boolean值的test方法。
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
另外它还提供了逻辑判断的经典”或与非“操作,分别对应or,and, negate方法。
使用示例
在1.8新提供的针对集合的流式操作接口中, Stream包含一个过滤的filter方法,它的参数就是一个Predicate接口,用于判断当前对象是否能通过过滤。
java.util.stream.Stream 类
/**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to each element to determine if it
* should be included
* @return the new stream
*/
Stream<T> filter(Predicate<? super T> predicate);
java.uti.function包扩展介绍之BiFunction,BiConsumer,BiPredicate
上面提到的Function,Consumer, Supplier,Predicate都是jdk1.8 java.uti.function包下面的类。我们打开这个包,就会发现除了这4个外还有许多诸BiFunction,BiConsumer, UnaryOperator这样的类。
Bi扩展
Bi是Binary(二元) 的缩写,考虑到我们实际生活中存在2个入参的情况(单个入参无法满足,例如比较操作),BiFunction(二元函数)有2个入参,最后也跟Function一样返回一个结果。
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
}
同样的, BiConsumer消费2个参数,BiPredicate接收2个参数,返回boolean值。
基本数据类型扩展
另外jdk还贴心的对消费、生产、使用基本数据类型(Int,Long,Double,Boolean)情况做了扩展:DoubleConsumer 只消费double数据, DoubleFunction 的入参是double数字,DoubleToIntFunction接收double,返回int。
public interface DoubleConsumer {
/**
* Performs this operation on the given argument.
*
* @param value the input argument
*/
void accept(double value);
...
}
public interface DoubleToIntFunction {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
int applyAsInt(double value);
}
一元扩展
UnaryOperator 是Function的一元形式,接收参数和返回结果是一个类型。
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
/**
* Returns a unary operator that always returns its input argument.
*
* @param <T> the type of the input and output of the operator
* @return a unary operator that always returns its input argument
*/
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
对应的基础类型扩展有IntUnaryOperator, 接受和返回类型都是int。类似的有 IntUnaryOperator, DoubleUnaryOperator
都是对常用类型的适配