一、Predicate
二、实战:判断List中以a开头的字符串
Stage 1: 创建方法
Stage 2: 调用方法
Stage 3: 执行结果
一、Predicate
-
断言型接口: T:入参类型,返回值类型 boolean
-
调用方法: boolean test(T t);
-
用途: 接收一个参数,用于判断是否满足一定的条件,过滤数据文章来源:https://uudwc.com/A/EvkMD
/**
* @param <T> the type of the input to the predicate
*/
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
二、实战:判断List中以a开头的字符串
Stage 1: 创建方法
public static List<String> filter(List<String> list, Predicate<String> predicate) {
List<String> results = new ArrayList<>();
list.forEach(s -> {
if (predicate.test(s)) {
results.add(s);
}
});
return results;
}
Stage 2: 调用方法
public static void main(String[] args) {
List<String> list = Arrays.asList("alis", "bron", "caiwen", "duo", "fanc", "abc");
List<String> results = filter(list, obj -> obj.startsWith("a"));
log.info(list.toString());
log.info(results.toString());
}
Stage 3: 执行结果
文章来源地址https://uudwc.com/A/EvkMD