首页 > 代码库 > Predicate接口和Consumer接口

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、结合实例

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));	}	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;	}}

  

 

Predicate接口和Consumer接口