Lambda表达式
Lambda表达式是一个匿名方法,将行为向数据一样进行传递。
匿名内部类实现的代码
button.addActionListener(new ActionListeer() {public void actionPerformed(ActionEvent event) {System.out.println("button clicked");}})
使用Lambda表达式改造
button.addActionListener(event -> System.out.println("button clicked"));
- 声明event参数的方式
- 使用匿名内部类,需要显式地声明参数类型ActionEvent event
 - Lambda表达式无需指定类型(javac根据程序上下文在后台推断出了event的类型),称为类型推断
 
 
Lambda表达式的形式
// 无参数,实现Runnable接口Runnable noArguments = () -> System.out.println("hellow world");// 包含一个参数ActionListener oneArgument = event -> System.out.println("button clicked");// 多行语句Runnable multiStatement = () -> {System.out.print("hello");System.out.print("world");}// 多个参数。这行代码不是将两个数字相加,而是创建一个函数,用来计算两个数字相加的结果。BinaryOperator<Long> add = (x, y) -> x + y;// 显示声明参数类型BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;
函数接口
函数接口是只有一个抽象方法的接口,用作Lambda表达式的类型。
JDK提供的核心函数接口:
| 接口 | 参数 | 返回类型 | 示例 | 
|---|---|---|---|
| Predicate | 
T | boolean | 这张唱片已经发行了吗? | 
| Consumer | 
T | void | 输出一个值 | 
| Function | 
T | R | 获得Artist对象的名字 | 
| Supplier | 
None | T | 工厂方法 | 
| UnaryOperator | 
T | T | 逻辑非(!) | 
| BinaryOperator | 
(T, T) | T | 求两个函数的乘积(*) | 
流
使用外部迭代
int count = 0;Iterator<Artist> iterator = allArtists.iterator();while(iterator.hasNext()) {Artist artist = iterator.next();if (artist.isFrom("London")) {count++;}}
使用内部迭代
long count = allArtists.stream().filter(artist -> artist.isFrom("London)).count();
stream()方法返回内部迭代的响应接口:Stream。
stream 是用函数式编程方式在集合类上进行复杂操作的工具。
