作者:微信小助手
发布时间:2021-11-05T09:27:20
Lamda 表达式非常方便,在项目中一般在 stream 编程中用的比较多。
List<Student> studentList = gen();
Map<String, Student> map = studentList .stream()
.collect(Collectors.toMap(Student::getId, a -> a, (a, b) -> a));
1. 确认 Lamda 表达式的类型
2. 找到要实现的方法
3. 实现这个方法
@FunctionalInterface
public interface Runnable {
public abstract void run();
}这就是一个标准的函数式接口。
因为只有一个抽象方法。而且这个接口上有个注解
// 没有实现任何抽象方法的接口
@FunctionalInterface
public interface MyRunnable {}
// 编译后控制台显示如下信息
Error:(3, 1) java:
意外的 @FunctionalInterface 注释
MyRunnable 不是函数接口
在 接口 MyRunnable 中找不到抽象方法
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {...}
}
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {...}
default Predicate<T> negate() {...}
default Predicate<T> or(Predicate<? super T> other) {...}
static <T> Predicate<T> isEqual(Object targetRef) {...}
static <T> Predicate<T> not(Predicate<? super T> target) {...}
}