Java8新特性之04函数式接口
04 函数式接口
函数式接口(Functional Interface)是指 只包含一个抽象方法 的接口。Java 8 引入了函数式接口的概念,以支持函数式编程的特性。
JDK 内置的函数式接口都加上了 @FunctionalInterface 注解,但是并非加这个注解的才是函数式接口,只要满足“只包含一个抽象方法”,就是函数式接口。
以下是函数式接口的一些特点和用途:
- 单一抽象方法:函数式接口只能包含一个抽象方法,可以有默认方法和静态方法,但只能有一个抽象方法。这个抽象方法定义了接口的核心功能。
- Lambda 表达式:函数式接口可以使用 Lambda 表达式来创建接口的实例。Lambda 表达式提供了一种简洁的方式来定义函数式接口的实现。
- 方法引用:函数式接口可以使用方法引用来引用已有的方法作为接口的实现。方法引用提供了一种更简洁的方式来表示函数式接口的实现。
- Java 8 Stream API:Java 8 的 Stream API 中广泛使用了函数式接口。Stream API 提供了一种流式操作的方式,可以对集合进行过滤、映射、排序等操作。
常用函数式接口
常用的函数式接口包括 Runnable、Comparator、Consumer、Function、Predicate 等。
Java 8 提供了一些内置的函数式接口,如 Supplier、UnaryOperator、BinaryOperator 等。
函数式接口常用默认(default)方法
Predicate
and
在使用 Predicate 接口时,可能需要进行判断条件的拼接,而 and() 方法相当于使用 && 来拼接两个判断条件。
例如:打印作家中年龄大于17并且姓名的长度大于1的作家。
当然这里用两个 filter() 也可以,或者是在一个 Predicate 里面用 && 连接判断。
先用匿名内部类实现:
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 17;
}
}.and(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getName().length() > 1;
}
}))
.forEach(System.out::println);
}
改用Lambda表达式:
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17).and(author -> author.getName().length() > 1))
.forEach(System.out::println);
}
or

or 与 and 类似,相当于用 || 来拼接两个判断条件。
negate

Negate 相当于在判断条件前面加了个 ! 取反。
例如:打印作家中年龄不大于17的作家。
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge() > 17;
}
}.negate())
.forEach(System.out::println);
}
转为Lambda表达式:
public static void main(String[] args) {
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17).negate())
.forEach(System.out::println);
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员小航
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果