1. 概述
只有一个抽象方法的接口我们称之为函数接口。
JDK的函数式接口都加上了**@FunctionalInterface** 注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。
2. 常见函数式接口
Consumer 消费接口
Consumer 是一个消费型接口,它对输入参数执行某种操作而不返回结果。其抽象方法为 accept(T t)。
public static void main(String[] args) {
Consumer<String> consumer=new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("consumer:"+s);
}
};
consumer.accept("hello,world");
}
//输出:consumer:hello,world
Function 计算转换接口
Function 是一个函数型接口,它接受一个参数并返回一个结果。其抽象方法为 apply(T t)。
public static void main(String[] args) {
Function<String, Integer> function = s -> s.length();
Integer length = function.apply("Hello, World!");
System.out.println("Length: " + length);
}
//Length: 13
Predicate 判断接口
Predicate 是一个谓词型接口,它对输入参数进行判断并返回一个布尔值。其抽象方法为 test(T t)。
public static void main(String[] args) {
Predicate<String> predicate = s -> s.isEmpty();
boolean result = predicate.test("");
System.out.println("Is empty: " + result);
}
//Is empty: true
Supplier 生产型接口
Supplier 是一个供给型接口,它不接受参数但返回一个结果。其抽象方法为 get()。
public static void main(String[] args) {
Supplier<String> supplier = () -> "Hello, World!";
String result = supplier.get();
System.out.println("Supplied: " + result);
}
//Supplied: Hello, World!
总结
Consumer:接收一个输入参数,执行一些操作,但不返回结果。
Function<T, R>:接收一个输入参数,执行计算或转换操作,并返回一个结果。
Predicate:接收一个输入参数,进行条件判断,返回一个布尔值。
Supplier:不接收输入参数,返回一个结果。
这些函数式接口广泛应用于 Java 8 的流操作和其他需要函数式编程的场景中,可以使代码更加简洁和易于理解。
3. 常用的默认方法
-
and
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件
例如:
打印作家中年龄大于17并且姓名的长度大于1的作家。
List<Author> authors = getAuthors(); Stream<Author> authorStream = authors.stream(); authorStream.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
我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。
例如:
打印作家中年龄大于17或者姓名的长度小于2的作家。
// 打印作家中年龄大于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.getName()));
-
negate
Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反
例如:
打印作家中年龄不大于17的作家。
// 打印作家中年龄不大于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()));