函数式接口是只包含一个抽象方法的接口。它们只能展示一种功能。从Java8开始,可以使用lambda表达式来表示函数式接口的实例。函数式接口可以有任意数量的默认方法。 Runnable
、 ActionListener
和 Comparable
是函数接口的一些示例。
在Java8之前,我们必须创建匿名的内部类对象或实现这些接口。
// Java program to demonstrate functional interface class Test { public static void main(String args[]) { // create anonymous inner class object new Thread(new Runnable() { @Override public void run() { System.out.println("New thread created"); } }).start(); } }
输出:
New thread created
从Java 8开始,我们可以将lambda表达式分配给它的函数接口对象,如下所示:
// Java program to demonstrate Implementation of // functional interface using lambda expressions class Test { public static void main(String args[]) { // lambda expression to create the object new Thread(()-> {System.out.println("New thread created");}).start(); } }
输出:
New thread created
@FunctionalInterface
@FunctionInterface注解用于确保函数接口不能有多个抽象方法。如果存在多个抽象方法,编译器会标记一条“ Unexpected@functioninterface annotation
”消息。但是,不强制使用此注释。
// Java program to demonstrate lamda expressions to implement // a user defined functional interface. @FunctionalInterface interface Square { int calculate(int x); } class Test { public static void main(String args[]) { int a = 5; // lambda expression to define the calculate method Square s = (int x)->x*x; // parameter passed and return type must be // same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); } }
输出:
java.util.function
这个 java.util.function
包是Java8中的包,它包含许多内置函数接口,如:
Predicate:Predicate接口有一个抽象方法测试,它为指定的参数提供一个布尔值作为结果。它的原型是
public interface Predicate { public boolean test(T t); }
BinaryOperator:BinaryOperator接口有一个抽象方法 apply
,它接受两个参数并返回相同类型的结果。它的原型是
public interface BinaryOperator { public T apply(T x, T y); }
Function:Function接口有一个抽象方法 apply
,它接受T类型的参数并返回 R
类型的结果
public interface Function { public R apply(T t); }
代码示例:
// A simple program to demonstrate the use // of predicate interface import java.util.*; import java.util.function.Predicate; class Test { public static void main(String args[]) { // create a list of strings List<String> names = Arrays.asList("Geek","GeeksQuiz","g1","QA","Geek2"); // declare the predicate type as string and use // lambda expression to create object Predicate<String> p = (s)->s.startsWith("G"); // Iterate through the list for (String st:names) { // call the test method if (p.test(st)) System.out.println(st); } } }
输出:
Geek GeeksQuiz Geek2
要点:
1. 函数式接口只有一个抽象方法,但可以有多个默认方法。
2. @FunctionInterface注解用于确保一个接口不能有多个抽象方法。此注解的使用是可选的。
3. 这个java.util.function函数包中包含许多Java8中的内置函数接口。