Java-Lambda

简介

​ lambda表达式就是函数编程,就是将一个函数作为方法的入参,本质上是以匿名内部类的方式实现。

eg:创建线程

1
new Thread(() -> System.out.println("Hello AaCopy")).start();

eg:集合排序

1
2
List<String> list = new ArrayList<>();
Collections.sort(list, (a, b) -> b.compareTo(a));

语法

(params) -> {expression}

params:

  • 参数列表数据类型省略
  • 没有参数列表时,使用()
  • 只有一个参数时,()可以省略,eg:a -> System.out.println(a)
  • 有多个参数时,(a, b)-> a+b

expression:

  • 只有一行代码时,{}、return、分号都可以省略
  • 有多行代码时,和正常方法一样写法

使用自定义函数式接口

  1. 定义函数(行为)接口,接口需要添加注解@FunctionalInterface,接口内只有一个需要被实现的方法,如果有其他方法,需要设置defalut
1
2
3
4
@FunctionalInterface
public interface OperFunction<R, T> {
R operator(T t1, T t2);
}
  1. 编写一个方法,参数为,需要操作的数据和函数接口
1
2
3
public static Integer operator(Integer x, Integer y, OperFunction<Integer, Integer> of) {
return of.operator(x, y);
}
  1. 调用方法时传入数据和lambda表达式
1
2
System.out.println(operator(2, 7, (x, y) -> x + y));
System.out.println(operator(5, 3, (x, y) -> x - y));

Java内置函数式接口

​ java内置的函数式接口放在java.util.function包下面,四大核心接口

  • 消费型接⼝:有⼊参,⽆返回值
1
2
3
public interface Consumer<T> {
void accept(T t);
}
  • 供给型接⼝:⽆⼊参,有返回值
1
2
3
public interface Supplier<T> {
T get();
}
  • 函数型接⼝:有⼊参,有返回值
1
2
3
public interface Function<T, R> {
R apply(T t);
}
  • 断⾔型接⼝:有⼊参,返回值类型是boolean
1
2
3
public interface Predicate<T> {
boolean test(T t);
}

⽅法引⽤与构造函数引⽤

  • 说明

    ​ ⽅法引⽤是⼀种更简洁易懂的lambda表达式,操作符是双冒号::,⽤来直接访问类或者实例已经存在的⽅法或构造⽅法

  • 语法

    左边是容器(可以是类名,实例名),中间是” :: “,右边是相应的⽅法名

    • 静态方法

      ClassName::methodName

    • 实例方法

      Instance::methodName

    • 构造函数

      ClassName::new

1
2
3
4
5
6
7
8
9
10
BiFunction<String, String, Boolean> biFun = String::contains;
boolean r = biFun.apply("abc", "ab");
System.out.println(r);
BiFunction<String, String, Boolean> biFun2 =(a, b) -> a.contains(b);
System.out.println(biFun2.apply("abc", "ab"));
Function<CharSequence, Boolean> fun = "abc"::contains;
System.out.println(fun.apply("ab"));

BiFunction<String, Integer, User> biFunction = User::new;
User user = biFunction.apply("aacopy", 18);