关注: Java提升营 ,最新文章第一时间送达, 10T 免费学习资料 随时领取!!!
一个 functional interface
是仅包含一个抽象方法的接口。他们只能做一个操作。从Java 8开始, lambda表达式
可用来表示 functional interface
的实例。 functional interface
可以有多个 默认方法
或 静态方法
。 Runnable
、 ActionListener
和 Comparable
都是 functional interface
的一些示例。
在Java 8之前,我们必须创建匿名内部类对象或实现这些接口。
<!-- more -->
// 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表达式
来代表 functional interface
的实例,如下所示:
// 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
注解的接口可以确保不能有多个抽象方法。如果存在多个抽象方法,则编译器会报“ Unexpected @FunctionalInterface 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 8中的 java.util.function
包 包含许多内置的 functional interface
,例如-
test
,该方法返回一个Boolean值。 public interface Predicate
{
public boolean test(T t);
}
apply
,该方法传入两个参数并返回相同类型的结果。 public interface BinaryOperator
{
public T apply(T x, T y);
}
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
functional interface
只有一个抽象方法,但可以有多个默认方法或静态方法。 @FunctionalInterface
注解用于确保接口不能具有多个抽象方法。此注释的使用是可选的。 java.util.function
包内包含Java 8中许多内置的 functional interface
。