1. Function<T, R>
-
描述: 接受一个参数,返回一个结果。
-
抽象方法:
R apply(T t)
-
使用场景: 数据转换、类型映射。
示例:
Function<String, Integer> lengthFunction = str -> str.length();
System.out.println(lengthFunction.apply("Hello")); // 输出 5
2. Consumer<T>
-
描述: 接受一个参数,不返回结果。
-
抽象方法:
void accept(T t)
-
使用场景: 执行某种操作,例如打印、记录日志。
示例:
Consumer<String> printConsumer = System.out::println;
printConsumer.accept("Hello World"); // 输出 Hello World
3. Supplier<T>
-
描述: 不接受参数,返回一个结果。
-
抽象方法:
T get()
-
使用场景: 延迟加载、生成对象或值。
示例:
Supplier<Double> randomSupplier = Math::random;
System.out.println(randomSupplier.get()); // 输出一个随机数
4. Predicate<T>
-
描述: 接受一个参数,返回一个布尔值。
-
抽象方法:
boolean test(T t)
-
使用场景: 条件判断、过滤数据。
示例:
Predicate<Integer> isEven = x -> x % 2 == 0;
System.out.println(isEven.test(4)); // 输出 true
5. BiFunction<T, U, R>
-
描述: 接受两个参数,返回一个结果。
-
抽象方法:
R apply(T t, U u)
-
使用场景: 两个值的组合或计算。
示例:
BiFunction<Integer, Integer, Integer> addFunction = (a, b) -> a + b;
System.out.println(addFunction.apply(5, 3)); // 输出 8
6. BinaryOperator<T>
-
描述: 接受两个相同类型的参数,返回相同类型的结果。
-
继承: 继承自
BiFunction<T, T, T>
-
抽象方法:
T apply(T t1, T t2)
-
使用场景: 两个值的操作(如最大值、最小值)。
示例:
BinaryOperator<Integer> maxFunction = Integer::max;
System.out.println(maxFunction.apply(10, 20)); // 输出 20
7. UnaryOperator<T>
-
描述: 接受一个参数,返回一个与输入类型相同的结果。
-
继承: 继承自
Function<T, T>
-
抽象方法:
T apply(T t)
-
使用场景: 对单个值的操作(如自增、自减)。
示例:
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5)); // 输出 25
8. BiConsumer<T, U>
-
描述: 接受两个参数,不返回结果。
-
抽象方法:
void accept(T t, U u)
-
使用场景: 同时处理两个值,例如记录日志。
示例:
BiConsumer<String, Integer> printBiConsumer = (name, age) ->
System.out.println(name + " is " + age + " years old");
printBiConsumer.accept("Alice", 25); // 输出 Alice is 25 years old
9. Comparator<T>
-
描述: 用于比较两个对象。
-
抽象方法:
int compare(T o1, T o2)
-
使用场景: 自定义排序。
示例:
Comparator<Integer> comparator = Integer::compare;
System.out.println(comparator.compare(10, 20)); // 输出 -1
扩展:函数式接口自定义
可以定义自己的函数式接口,只需要保证接口中只有一个抽象方法,并使用 @FunctionalInterface
注解。
示例:
@FunctionalInterface
interface MyFunctionalInterface {
void execute(String message);
}
MyFunctionalInterface myFunc = message -> System.out.println(message);
myFunc.execute("Custom Functional Interface!"); // 输出 Custom Functional Interface!
总结表格
函数式接口 | 抽象方法签名 | 使用场景 |
---|---|---|
Function<T, R> | R apply(T t) | 用于将一种类型的数据转换为另一种类型,例如字符串转换为其长度、对象转换为其属性值等。 |
Consumer<T> | void accept(T t) | 执行某些操作但不返回结果,例如打印日志、保存数据或发送通知。 |
Supplier<T> | T get() | 用于提供一个结果,通常用于延迟计算、生成新对象或返回固定值。 |
Predicate<T> | boolean test(T t) | 用于条件判断,常用于过滤集合、验证输入是否合法或检查某些条件是否成立。 |
BiFunction<T, U, R> | R apply(T t, U u) | 处理两个输入值并生成一个结果,例如将两个数相加、两个字符串拼接或组合两个对象为新对象。 |
BinaryOperator<T> | T apply(T t1, T t2) | 处理两个相同类型的值并生成一个相同类型的结果,例如计算两个数的最大值、最小值或相加。 |
UnaryOperator<T> | T apply(T t) | 对单个值进行操作并返回一个相同类型的结果,例如自增、自减或对字符串进行转换操作。 |
BiConsumer<T, U> | void accept(T t, U u) | 同时处理两个输入值但不返回结果,例如打印两个值的关系、记录两个参数的日志等。 |
Comparator<T> | int compare(T o1, T o2) | 用于比较两个对象的大小,通常用于排序操作,例如对集合中的对象进行升序或降序排列。 |