4-5 Java新特性玩转JDK8之函数式编程 Predicate
如果您还没有阅读本章须知,请先阅读➡ 本章须知
资料
- Predicate: 断言型接口:有入参,有返回值,返回值类型确定是boolean
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
用途
- 接收一个参数,用于判断是否满足一定的条件,过滤数据。
使用示例
过滤List集合中,以a开头的字符串。
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("awewrwe","vdssdsd","aoooo","psdddsd");
List<String> results = filter(list,obj->obj.startsWith("a"));
System.out.println(results);
// 打印结果 [awewrwe, aoooo]
}
public static List<String> filter(List<String> list, Predicate<String> predicate) {
List<String> results = new ArrayList<>();
for (String str : list) {
if (predicate.test(str)) {
results.add(str);
}
}
return results;
}
}
原文地址:
https://www.yuque.com/books/share/94d7e9ce-40a5-4878-97f2-c6297f679886