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
1 Predicate<Integer> pre = x -> x >= 5; 2 System.out.println(pre.test(9));//输出结果为true
- consumer
1 import java.util.Collection; 2 import java.util.HashSet; 3 import java.util.function.Predicate; 4 import java.util.function.Consumer; 5 6 public class PreCon { 7 public static void main(String []args){ 8 Collection<String> c=new HashSet<String>(); 9 c.add("!"); 10 c.add("java"); 11 c.add("hao"); 12 c.add("ni"); 13 c.add("zhe"); 14 System.out.println(findSet(c,obj->System.out.println(obj),obj->((String)obj).length()<3)); 15 16 //使用Lambda表达式(目标类型是Predicate)过滤集合 17 c.removeIf(ele -> ((String)ele).length() < 10); 18 System.out.println(c); 19 } 20 21 public static int findSet(Collection collection, Consumer consumer, 22 Predicate predicate) { 23 int n = 0; 24 for (Object obj : collection) { 25 if (predicate.test(obj)) { 26 n++; 27 consumer.accept(obj); 28 } 29 } 30 return n; 31 } 32 }