一、java.util.function 包中的函数式接口定义
1. Function<T, R>
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}作用:将一个类型
T转换为另一个类型R。示例:
String -> Integer
2. Consumer<T>
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}作用:对一个输入值进行消费(不返回结果)。
示例:
String -> void
3. Supplier<T>
@FunctionalInterface
public interface Supplier<T> {
T get();
}作用:提供一个值,不接受参数。
示例:
void -> String
4. Predicate<T>
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}作用:对一个输入值进行判断,返回布尔值。
示例:
Integer -> boolean
5. UnaryOperator<T>
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
T apply(T t);
}作用:对一个输入值进行操作并返回相同类型的输出。
示例:
String -> String
6. BinaryOperator<T>
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
T apply(T t1, T t2);
}作用:对两个同类型输入值进行操作并返回同类型结果。
示例:
Integer + Integer -> Integer
7. BiFunction<T, U, R>
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}作用:对两个不同类型的输入值进行处理,返回一个结果。
示例:
String, Integer -> String
8. BiConsumer<T, U>
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}作用:对两个输入值进行消费(不返回结果)。
示例:
String, Integer -> void
9. BiPredicate<T, U>
@FunctionalInterface
public interface BiPredicate<T, U> {
boolean test(T t, U u);
}作用:对两个输入值进行判断,返回布尔值。
示例:
String, Integer -> boolean
二、其他常用函数式接口(如 Runnable, Callable 等)
虽然这些不是 java.util.function 包的一部分,但它们也是常见的函数式接口:
10. Runnable
@FunctionalInterface
public interface Runnable {
void run();
}作用:无参数、无返回值的函数式接口。
示例:
void -> void
11. Callable<V>
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}作用:执行任务并返回结果,可能抛出异常。
示例:
void -> Object
评论区