函数式接口 java.util.function
- Predicate: 有输入且只输出布尔值
a predicate (boolean-valued function) of one argument,
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate接口包含negate(非)、and(与)和or(非)方法
default Predicate<T> negate() {
return (t) -> !test(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);
}
- Function:有输入有输出
a function that accepts one argument and produces a result
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
- Consumer:有输入无输出
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
- Supplier:无输入有输出
@FunctionalInterface
public interface Supplier<T> {
T get();
}
- Operator:输入和输出为相同类型
- UnaryOperator
Represents an operation on a single operand that produces a result of the same type as its operand.
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
- BinaryOperator
Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
}
使用Lambda表达式实现函数式接口的抽象方法:
例
Predicate<Integer> empty = x -> x > 0;
System.out.println(empty.test(1));