5.函数式接口
5.1 概述
只有一个抽象方法的接口我们称之为函数接口。
JDK的函数式接口都加上了@Functionalinterface注解进行标识。但是无论是
否加上该注解只要接口中只有一个抽象方法,都是函数式接口。
5.2 常见函数式接口
- Consumer消费接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费
- Function计算转换接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回
- Predicate判断接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中传入的参数条件判断,返回判断结果
- Supplier生产型接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回
5.3常见的默认方法
自己去定义方法的时候才会用到(这边作为了解即可)
- and
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件
例如:
//打印作家中年龄大于17并且姓名的长度大于1的作家
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(author -> System.out.println(author.getAge()+"---"+author.getName()));
//相当于
authors.stream()
.filter(author -> author.getAge()>17&&author.getName().length()>1).forEach(author -> System.out.println(author.getAge()+"---"+author.getName()));
- or
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件
例如:
//打印作家中年龄大于17或者姓名的长度小于2的作家
List<Author> authors = getAuthors();
authors.stream()
.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge()>17;
}
}.or(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getName().length()<2;
}
})).forEach(author -> System.out.println(author.getAge()+"---"+author.getName()));
- negate
Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反
例如:
//打印作家中年龄不大于17的作家
List<Author> authors = getAuthors();
authors.stream()
.filter(new Predicate<Author>() {
@Override
public boolean test(Author author) {
return author.getAge()>17;
}
}.negate()).forEach(author -> System.out.println(author.getAge()));