Lambda表达式

55 阅读2分钟

函数式编程思想概述

在数学中,函数就是有输入量、输出量的一套计算方案,也就是“拿什么东西做什么事情”。相对而言,面向对象过分强调“必须通过对象的形式来做事情”,而函数式思想则尽量忽略面向对象的复杂语法——强调做什么,而不是以什么形式做

面向对象的思想:

​ 做一件事情,找一个能解决这个事情的对象,调用对象的方法,完成事情.

函数式编程思想:

​ 只要能获取到结果,谁去做的,怎么做的都不重要,重视的是结果,不重视过程

lambda表达式的标准格式

(参数列表) -> {...}

Lambda的使用前提

Lambda的语法非常简洁,完全没有面向对象复杂的束缚。但是使用时有几个问题需要特别注意:

  1. 使用Lambda必须具有接口,且要求接口中有且仅有一个抽象方法。 无论是JDK内置的RunnableComparator接口还是自定义的接口,只有当接口中的抽象方法存在且唯一时,才可以使用Lambda。
  2. 使用Lambda必须具有上下文推断。 也就是方法的参数或局部变量类型必须为Lambda对应的接口类型,才能使用Lambda作为该接口的实例。

备注:有且仅有一个抽象方法的接口,称为“函数式接口”。

public interface Cats {
  int eat(int a,int b);
}

public class Demo1 {
  public static void main(String[] args) {
    /*fun(10, 15, new Cats() {
      @Override
      public int eat(int a, int b) {
        return a+b;
      }
    });*/

    //lambda表达式
    fun(12,23,(a,b)->a+b);
    
  }
  public static void fun(int a,int b,Cats cats){
    int num = cats.eat(a,b);
    System.out.println(num);
  }
}

方法引用和构造器引用

1、引用类方法

@FunctionalInterface
interface Converter{
    Integer convert(String from);
}

Converter converter1 = from -> Integer.valueOf(from)
    
Converter converter1 = Integer::valueOf;

2、引用特定对象的实例方法

Converter converter2 = from -> "fkit.org".indexOf(from);

Converter converter1 = "fkit.org"::valueOf;

3、引用某类对象的实例方法

@FunctionalInterface
interface MyTest{
    String test(String a, int b, int c);
}

MyTest mt = (a,b,c) -> a.substring(b,c);

MyTest mt = String::substring;

4、引用构造器

@FunctionalInterface
interface YourTest{
    JFrame win(String title);
}

YourTest yt = (String a) -> new JFrame(a)
    
YourTest yt = JFrame::new