在Java中,Function
、BiFunction
、Supplier
是一些常用的函数式接口,用于表示不同类型的函数。下面是对它们的介绍以及一些其他相关的函数式接口:
-
Function 接口:
- 描述: 接受一个参数,返回一个结果。
- 方法:
apply(T t)
,接受一个输入参数并返回一个结果。 - 示例:
Function<String, Integer> strLength = s -> s.length(); int length = strLength.apply("Hello"); // 返回 5
-
BiFunction 接口:
- 描述: 接受两个参数,返回一个结果。
- 方法:
apply(T t, U u)
,接受两个输入参数并返回一个结果。 - 示例:
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; int result = add.apply(3, 5); // 返回 8
-
Supplier 接口:
- 描述: 不接受任何参数,返回一个结果。常用于生成或提供数据。
- 方法:
get()
,返回一个结果。 - 示例:
Supplier<Double> randomValue = () -> Math.random(); double value = randomValue.get(); // 返回一个随机数
-
Consumer 接口:
- 描述: 接受一个参数,但没有返回值。常用于对输入进行消费操作。
- 方法:
accept(T t)
,接受一个输入参数。 - 示例:
Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase()); printUpperCase.accept("hello"); // 输出 "HELLO"
-
Predicate 接口:
- 描述: 接受一个参数,返回一个 boolean 值。常用于进行条件判断。
- 方法:
test(T t)
,对给定的输入值进行判断。 - 示例:
Predicate<Integer> isEven = n -> n % 2 == 0; boolean result = isEven.test(4); // 返回 true
-
UnaryOperator 接口:
- 描述: 继承自 Function 接口,接受一个参数,返回一个与参数类型相同的结果。
- 方法:
apply(T t)
,接受一个输入参数并返回一个结果。 - 示例:
UnaryOperator<Integer> square = x -> x * x; int result = square.apply(3); // 返回 9
-
BinaryOperator 接口:
- 描述: 继承自 BiFunction 接口,接受两个参数,返回一个与参数类型相同的结果。
- 方法:
apply(T t, U u)
,接受两个输入参数并返回一个结果。 - 示例:
BinaryOperator<Integer> add = (a, b) -> a + b; int result = add.apply(3, 5); // 返回 8
这些函数式接口使得在Java中更容易实现函数式编程的概念,通过Lambda表达式或方法引用,可以简洁地表示各种不同类型的函数。