public static <E> int calAll(Collection<E> co,Predicate<E> pr) {
int total = 0;
for(E obj : co) {
if(pr.test(obj)) {//我在这里认为要检验的是集合从而惯性地填写了集合名co其实我要检测的是元素是obj这个要完成集合元素赋值的临时变量
total++;
}
}
return total;
}
public static void main(String[] args) {
//创建集合
Collection<String> coll = new HashSet<>();
coll.add(new String("asd"));
coll.add(new String("assd"));
coll.add(new String("tas"));
//使用Predicate函数式接口的方法来实现过滤掉不符合条件的元素
coll.removeIf(ele->((String)ele).length() < 4);
System.out.println(coll);
//完成统计
System.out.println(calAll(coll,ele->((String)ele).length()<3));
System.out.println(calAll(coll, ele1->((String)ele1).equals("tas")));
}
Predicate的使用重要,多看多理解
最新推荐文章于 2024-04-29 11:34:15 发布