Java内置函数式接口
只包含一个抽象方法的接口,称为函数式接口。
可以通过Lambda 表达式来创建该接口的对象。(若Lambda 表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
在任意函数式接口上设置@FunctionalInterface注解,这样做可以检查它是否是一个函数式接口,同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。在此之前的PPT中,我们已经定义过函数式接口,但是我们不可能每次都要自己定义函数式接口,实在是太麻烦了。所以,Java内置了函数式接口在java.util.function包下
Predicate<T> 断言型接口
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
该类型的接口,在名称旁添加了一个泛型 T,该泛型是用于做函数参数的类型
并且该接口中的函数返回值是 boolean 所以可以断言程序执行结果是否正确
实例
package com.test.demo23;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class SimplePredicateExample {
public static void main(String[] args) {
// 创建一个字符串列表
List<String> words=new ArrayList<>();
words.add("apple");
words.add("banana");
words.add("cherry");
words.add("date");
words.add("fig");
// 创建一个 Predicate 实例,用于筛选长度大于等于 5 的字符串
Predicate<String> isLongWord=word->word.length()>=5;
// 使用 Predicate 进行筛选
List<String> longWords=filterWords(words,isLongWord);
// 打印输出筛选结果
System.out.println("长度大于等于 5 的单词列表: " + longWords);
}
public static List<String> filterWords(List<String> words, Predicate<String> predicate) {
List<String> filteredWords = new ArrayList<>();
for (String word : words) {
if (predicate.test(word)) {
filteredWords.add(word);
}
}
return filteredWords;
}
}
结果:
长度大于等于 5 的单词列表: [apple, banana, cherry]