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>