为了配合Lambda表达式的使用,为了简化代码编写的过程,JAVA定义了函数式接口的概念。一个接口,有且仅有一个抽象方法,可以不限default和static方法数量,并且被注解@FunctionalInterface所修饰,我们认为这种接口是函数式接口。
函数式接口和接口一样,本身没有含义。实现并使用此接口的对象得益于接口定义的参数数量和返回类型,在约定的情况下完成工作。使用函数式接口能提高工作效率,并且让代码更便于阅读和理解。
所有函数式接口位于:java.util.function 包内
1. Predicate接口
Predicate 接口只有一个参数,返回boolean类型。该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非)
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
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> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
除了上文说的test抽象方法,此类中还存在四个实现方法。
三个默认方法and、or、negate分别是与、或、非。将传入条件和自身二元操作。
2. Function接口
Function 接口有一个参数并且返回一个结果,并附带了一些可以和其他函数组合的默认方法(compose, andThen)泛型两个参数类型,第一个用来确定参数类型,第二个用来确定返回类型。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
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;
}
可以使用compose和andThen两个方法,在此类操作前后进行其他操作。
3. Supplier接口
Supplier接口返回一个任意范型的值,和Function接口不同的是该接口没有任何参数。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
4. Consumer 接口
Consumer 接口表示执行在单个参数上的操作。
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
5.Comparator 接口
Comparator不再function包内,在java.util下。Java8在Comparator接口中添加了多种默认方法。但是最实用的还是compare方法,其他的辅助方法不用记,直接实现compare方法即可。