Predicate接口和Consumer接口

Predicate和Consumer接口是集合操作中常用到的俩个接口:

1、Predicate

public interface Predicate<T>{
boolean test(T t);//进行某些逻辑判断并返回一个boolean值
}

2、Consumer

public interface Consumer<T>{
void accept(T t);//对于给定的对象进行操作
}

3、结合实例

  • predicate
 Predicate<Integer> pre = x -> x >= 5;
System.out.println(pre.test(9));//输出结果为true
  • consumer
 import java.util.Collection;
import java.util.HashSet;
import java.util.function.Predicate;
import java.util.function.Consumer; public class PreCon {
public static void main(String []args){
Collection<String> c=new HashSet<String>();
c.add("!");
c.add("java");
c.add("hao");
c.add("ni");
c.add("zhe");
System.out.println(findSet(c,obj->System.out.println(obj),obj->((String)obj).length()<3)); //使用Lambda表达式(目标类型是Predicate)过滤集合
c.removeIf(ele -> ((String)ele).length() < 10);
System.out.println(c);
} public static int findSet(Collection collection, Consumer consumer,
Predicate predicate) {
int n = 0;
for (Object obj : collection) {
if (predicate.test(obj)) {
n++;
consumer.accept(obj);
}
}
return n;
}
}

 

 

上一篇:微信小程序开发--背景图显示


下一篇:docker私服