1. 内置函数式接口由来
lambda表达式的前提是需要有函数式接口。而且lambda表达式使用时不关心接口名,抽象方法名;只关心抽象方法的参数列表和返回值类型。因此为了让我们使用lambda方便,JDK提供了大量的常用的函数时接口。
2. 常用内置函数式接口

2.1 Supplier接口
@FunctionalInterface
public interface Supplier<T> {
T get();
}
2.2 Consumer接口
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
2.3 Function接口
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
2.4 Predicate接口
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
3 Supplier接口
供给型接口,对应的lambda表达式需要“对外提供”一个符合泛型类型的对象数据,也就是lambda表达式必须有返回值。
@FunctionalInterface
public interface Supplier<T> {
T get();
}
通过Supplier接口中的get方法可以得到一个值并返回,无参数有返回值的接口方法。
lambda相当于重写了这个get抽象方法。


可以将lambda堪称是一个由参数和方法体的函数,
调用这个printMax方法,然后printMax方法内部,当执行supplierd的唯一抽象方法get方法的时候,其实就是运行lambda表达式的时候。
4 Consumer接口
和Supplier接口刚好相反,他不是产生一个数据,而是消费一个数据,即lambda表达式方法体没有返回值
@FunctionalInterface
public interface Consumer<T> {
public abstract void accept(T t);
}
代码如下:
public class Demo02Consumer {
public static void main(String[] args){
printHello((String str)->{
System.out.println(str.toUpperCase());
});
}
public static void printHello(Consumer<String > consumer){
consumer.accept("hello");
}
}
Consumer中还有一个默认default方法andThen
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
如果一个方法有两个接口实现都需要调用accept,则需要这样

可以通过andThen的方法简化

5 Function接口
Function接口刚好相反,需要获取一个类型的数据,然后处理得到另一个类型的数据返回,前者称为前置条件,后者称为后置条件,必须有参数有返回值。
@FunctionalInterface
public interface Function<T, R> {
public abstract R apply(T t);
}
代码如下:

其也有andThen的默认方法

6 Predicate接口
我们需要对某种类型的数据进行判断,从而得到一个boolean值结果,这时可以使用这个接口
@FunctionalInterface
public interface Predicate<T> {
public abstract boolean test(T t);
}
代码如下:

Predicate的and no negate方法
即使两个返回值的或与非方法。

网友评论