内置四大核心函数式接口
我们每次使用Lambda表达式都需要一个函数式接口,而且这个接口大同小异,每次都新建一个函数式接口是比较繁琐的,Java8为我们内置了四大核心函数式接口:
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
Concumer<T>消费型接口 | T | void | 对类型为T的对象应用操作,抽象方法:void accept(T t) |
Supplier<T>供给型接口 | 无 | T | 返回类型为T的对象,抽象方法:T get() |
Function<T, R>函数型接口 | T | R | 对类型为T的对象进行操作,并返回R类型的对象。抽象方法:R apply(T t) |
Predicate<T>断言型接口 | T | boolean | 确定类型为T的对象是否满足某种约束,并返回boolean 值。包含方法boolean test(T t) |
内置核心函数式接口的定义:
1、消费型接口
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
2、供给型接口
@FunctionalInterface
public interface Supplier<T> {
T get();
}
3、函数型接口
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
4、断言型接口
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
其他内置函数式接口
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
BiFunction<T, U, R> | T,U | R | 对类型为 T, U 的参数进行操作,返回 R 类型的结果。包含方法为R apply(T t, U u); |
UnaryOperator<T>(Function子接口) | T | T | 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法为T apply(T t); |
BinaryOperator<T>(BiFunction子接口) | T,T | T | 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为 T apply(T t1, T t2); |
ToIntFunction<T> ToLongFunction<T> ToDoubleFunction<T> | T | int long double | 分别计算int、long、double值的函数 |
IntFunction<R> LongFunction<R> DoubleFunction<R> | int long double | R | 参数分别为int、long、double类型的函数 |