函数式接口
5.1 概述
函数式接口:有且仅有一个抽象方法的接口
Java中的函数式编程体现就是Lambda表达式,所以函数式接口就是适用于Lambda使用的接口
只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利进行推导
JDK的函数式接口上都有@FunctionalInterface注解标识。
5.2 常见的函数式接口
-
Consumer 消费接口
根据其中的抽象方法的参数进行消费,例如:打印
-
Function 计算转换接口
根据抽象方法可以知道需要参数列表和返回值,将参数通过转换后转为返回值返回
-
Predicate 判断接口
根据传入的参数进行判断,返回Boolean值
-
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));
-
or
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));
-
negate
Predicate中的方法,相当与取反(!)
例如:打印作家不大于17的作家
List<Author> authors = getAuthors(); authors.stream() .filter(new Predicate<Author>() { @Override public boolean test(Author author) { return author.getAge()>19; } }.negate()) .forEach(author -> System.out.println(author));