Lambda表达式

Lambda表达式是一个匿名方法,将行为向数据一样进行传递。

匿名内部类实现的代码

  1. button.addActionListener(new ActionListeer() {
  2. public void actionPerformed(ActionEvent event) {
  3. System.out.println("button clicked");
  4. }
  5. })

使用Lambda表达式改造

  1. button.addActionListener(event -> System.out.println("button clicked"));
  • 声明event参数的方式
    • 使用匿名内部类,需要显式地声明参数类型ActionEvent event
    • Lambda表达式无需指定类型(javac根据程序上下文在后台推断出了event的类型),称为类型推断

Lambda表达式的形式

  1. // 无参数,实现Runnable接口
  2. Runnable noArguments = () -> System.out.println("hellow world");
  3. // 包含一个参数
  4. ActionListener oneArgument = event -> System.out.println("button clicked");
  5. // 多行语句
  6. Runnable multiStatement = () -> {
  7. System.out.print("hello");
  8. System.out.print("world");
  9. }
  10. // 多个参数。这行代码不是将两个数字相加,而是创建一个函数,用来计算两个数字相加的结果。
  11. BinaryOperator<Long> add = (x, y) -> x + y;
  12. // 显示声明参数类型
  13. 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 求两个函数的乘积(*)

使用外部迭代

  1. int count = 0;
  2. Iterator<Artist> iterator = allArtists.iterator();
  3. while(iterator.hasNext()) {
  4. Artist artist = iterator.next();
  5. if (artist.isFrom("London")) {
  6. count++;
  7. }
  8. }

使用内部迭代

  1. long count = allArtists.stream()
  2. .filter(artist -> artist.isFrom("London))
  3. .count();

stream()方法返回内部迭代的响应接口:Stream。

stream 是用函数式编程方式在集合类上进行复杂操作的工具。