Java函数式接口介绍及示例
Java 8引入了函数式接口,为Java编程语言添加了函数式编程特性。函数式接口是只定义了一个抽象方法的接口。这意味着它们只有一个未实现的方法,可以通过lambda表达式来实现。
Java函数式接口的定义方法是注解@FunctionalInterface,也可以手动定义只有一个抽象方法的接口。以下是一个自定义函数式接口的示例:
@FunctionalInterface // 声明为函数式接口
public interface MyFunction {
void operate();
}
实现该函数式接口的lambda表达式示例:
MyFunction mf = () -> System.out.println("Hello, World!");
mf.operate(); // 输出:Hello, World!
Java内置了一些常用的函数式接口,包括:
#### 1. Consumer接口
Consumer接口表示接收一个参数并且不返回任何结果的操作。它只有一个accept()方法,该方法接收一个泛型参数。
Consumer<String> consumer = (x) -> System.out.println(x.toUpperCase());
consumer.accept("hello"); // 输出:HELLO
#### 2. Supplier接口
Supplier接口表示一个产生结果的操作。它只有一个get()方法,该方法不接收任何参数。
Supplier<String> supplier = () -> "Hello"; System.out.println(supplier.get()); // 输出:Hello
#### 3. Predicate接口
Predicate接口表示一个谓词(判断条件),它接收一个泛型参数并返回一个布尔值。
Predicate<Integer> predicate = (x) -> x > 10; // 是否大于10的判断条件 System.out.println(predicate.test(5)); // 输出:false System.out.println(predicate.test(15)); // 输出:true
#### 4. Function接口
Function接口表示一个将一个参数映射为另一个参数的操作。它接收两个泛型参数, 个参数表示输入,第二个参数表示输出。
Function<String, Integer> function = (x) -> x.length();
System.out.println(function.apply("hello")); // 输出:5
除了以上介绍的四种,Java中还有很多其他函数式接口,例如:
#### 5. Runnable接口
Runnable接口表示一个没有参数和返回值的操作。
Runnable runnable = () -> System.out.println("Hello, World!");
new Thread(runnable).start(); // 输出:Hello, World!
#### 6. BiConsumer接口
BiConsumer接口表示接收两个参数并且不返回任何结果的操作。
BiConsumer<Integer, Integer> biConsumer = (x, y) -> System.out.println(x + y); biConsumer.accept(1, 2); // 输出:3
#### 7. BiFunction接口
BiFunction接口表示一个将两个参数映射为另一个参数的操作。
BiFunction<Integer, Integer, String> biFunction = (x, y) -> "Result: " + (x + y); System.out.println(biFunction.apply(1, 2)); // 输出:Result: 3
#### 8. BiPredicate接口
BiPredicate接口表示一个接收两个参数并返回布尔值的判断条件。
BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
System.out.println(biPredicate.test("hello", "world")); // 输出:false
System.out.println(biPredicate.test("hello", "hello")); // 输出:true
Java的函数式接口使得函数式编程成为了Java编程语言的重要特性。使用lambda表达式实现函数式接口的方式简洁高效,可以大大提高代码的可读性和编写效率。使用Java的函数式接口可以实现更加灵活的编程模式,可以用来处理集合、流等多种数据类型。
